Practical post

641 81 0
Practical post

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Practical PostgreSQL Prev Next Appendix A Multibyte Encoding Types Table A-1 lists the various multibyte encoding types supported by PostgreSQL, as of version 7.1.x These encoding types are only available if PostgreSQL was configured with the -enable-multibyte flag (see Chapter 2) A database can be created with a default encoding type if SQL_ASCII is not desired Table A-1 Multibyte Encoding Types Encoding Type SQL_ASCII EUC_JP Integer EUC_CN EUC_KR EUC_TW UNICODE MULE_INTERNAL LATIN1 LATIN2 LATIN3 LATIN4 10 LATIN5 11 KOI8 WIN ALT 12 13 14 Prev Appendixes Home Up Description Plain ASCII format Japanese Extended UNIX Code Chinese Extended UNIX Code Korean Extended UNIX Code Taiwan Extended UNIX Code UTF-8 Unicode Mule internal type ISO 8859-1 (English, with some European languages) ISO 8859-2 (English, with some European languages) ISO 8859-3 (English, with some European languages) ISO 8859-4 (English, with some European languages) ISO 8859-5 (English, with some European languages) KOI8-R Windows CP1251 Windows CP866 Next Backend Options for postgres This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Practical PostgreSQL Prev Next Appendix A Multibyte Encoding Types Table A-1 lists the various multibyte encoding types supported by PostgreSQL, as of version 7.1.x These encoding types are only available if PostgreSQL was configured with the -enable-multibyte flag (see Chapter 2) A database can be created with a default encoding type if SQL_ASCII is not desired Table A-1 Multibyte Encoding Types Encoding Type SQL_ASCII EUC_JP Integer EUC_CN EUC_KR EUC_TW UNICODE MULE_INTERNAL LATIN1 LATIN2 LATIN3 LATIN4 10 LATIN5 11 KOI8 WIN ALT 12 13 14 Prev Appendixes Home Up Description Plain ASCII format Japanese Extended UNIX Code Chinese Extended UNIX Code Korean Extended UNIX Code Taiwan Extended UNIX Code UTF-8 Unicode Mule internal type ISO 8859-1 (English, with some European languages) ISO 8859-2 (English, with some European languages) ISO 8859-3 (English, with some European languages) ISO 8859-4 (English, with some European languages) ISO 8859-5 (English, with some European languages) KOI8-R Windows CP1251 Windows CP866 Next Backend Options for postgres This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Practical PostgreSQL Prev Next Appendix B Backend Options for postgres The postgres program is the actual backend server that processes SQL statements It is generally not called directly, but invoked through the multiuser postmaster process It can be helpful to know the options available to this program, however, as they can be called indirectly through the postmaster 's -o  flag The following syntax diagram shows the options recognized by postgres: postgres [ [ [ [ -A -D -i -s { | } ] [ -B buffers ] [ -c name= value ] datadir ] [ -e ] [ -E ] [ -f { s | i | n | m ] [ -L ] [ -N ] [ -o file-name ] [ -O ] [ -P | -t { pa | pl | ex } ] [ -S sort_mem ] [ -W postgres [ [ [ [ -A -D -L -s { | } ] [ -B datadir ] [ -e ] ] [ -o file-name | -t { pa | pl | [ -d debug-level ] | h } ] [ -F ] ] num ] database buffers ] [ -c name= value ] [ -d debug-level ] [ -f { s | i | n | m | h } ] [ -F ] [ -i ] ] [ -O ] [ -p database ] [ -P ] ex } ] [ -S sort_mem ] [ -v version ] [ -W num -A { | } The run-time assertion check parameter This enables debugging, if the debugging option was enabled during compilation of PostgreSQL This parameter should only be used by knowledgeable developers working on PostgreSQL -B buffers The number of shared-memory disk buffers that postmaster will allocate for use by the backend By default, this is 64 Note: The buffers value passed to -B must be at least twice the number supplied for the -N parameter -c name=value An arbitrary run-time configuration, setting name to value Any configuration settings found in the postgresql.conf file (within the database cluster's data directory) may be over-ridden with this option -d debug_level The debug level, which determines the amount of debugging output that will be logged by the backend The default is With a higher the debug_level number, more output will be generated Values as high as are reasonable for normal use, though this can log a great deal of information Note: Unless the standard output and standard error streams from postmaster are redirected to a file (e.g., from the shell, or with the -l option to pg_ctl) all debugging information will be displayed to the controlling This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com to pg_ctl) all debugging information will be displayed to the controlling terminal session of the postmaster process -D datadir The data directory of the intended database cluster If this is not supplied, postmaster will use either the value of the PGDATA environment variable, or the /data path off of the path defined in the POSTGRESHOME environment variable If neither environment variable is set, the default compile-time directory is used (e.g., /usr/local/pgsql/data) -e The European date style parameter This causes PostgreSQL to assume that dates such as 3/2/2001 are day-first rather than month-first It also causes PostgreSQL to display the day before the month (e.g., dd/mm/yyyy) when displaying dates -E The verbose echo parameter Causes all passed statements to be output (e.g., to the controlling terminal session, or to the server log) -f { s | i | n | m | h } The forbid parameter, which can forbid the use of certain scan and join methods The following options may follow the -f: s Forbids sequential scans i Forbids index scans n Forbids nested loops m Forbids merge joins h Forbids hash joins -F The fsync-disabling option Using this increases performance at the risk of data corruption in the event that the operating system or physical hardware crashes unexpectedly Be sure you know what you are doing before you use this parameter! -i This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com The -i parameter disables query execution, and causes PostgreSQL to only show the plan tree -L The lock-disabling parameter This turns off the ability to lock in PostgreSQL -N The -N parameter disables the use of a newline as a statement delimiter -O The -O parameter allows system tables to be modified -p database The postmaster parameter, indicating that this postgres instance was started by postmaster connecting to database This causes postgres to make different decisions about memory management and file descriptors -P The -P parameter causes PostgreSQL to ignore system indices when scanning and updating system tuples This option is required by the REINDEX command when indexing system tables -s The statistics parameter This causes PostgreSQL to display processing time and other statistics after each query, which can be helpful in benchmark tests, or for tuning the amount of buffers you make available with the -B parameter -S sort_mem The amount of memory to be allocated for internal sorting and hashes before falling back on temporary hard disk files sort_mem is a numeric value, in kilobytes, and defaults to 512 For complex statements, several sorts or hashes may run simultaneously; each one will be allocated up to the value specified by sort_mem before using temporary disk space -t { pa | pl | e } The timing statistics parameter, specific to only one of the major postgres components The following are the valid options that may follow the -t parameter: pa Times the parser component pl This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Times the planner component e Times the executor component The -t and -s options are mutually exclusive -v version The protocol version parameter This option sets the internal version number of the frontend-to-backend protocol -W num The wait parameter Specifying this value causes postgres to wait for num seconds before starting up, allowing a developer time to attach a debugger Prev Multibyte Encoding Types Home Up Next Binary COPY Format This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Practical PostgreSQL Prev Next Appendix C Binary COPY Format Table of Contents The Header Tuples Trailer In addition to saving data in text format, PostgreSQL can also save COPY output in its own binary format This is the format compiled programs are stored in, which is not readable by normal text editors The Header The PostgreSQL binary file header contains 24 bytes of fixed fields, and a variable length header extension area The fixed fields are as follows: Signature Field A 12-byte sequence, which is literally: PGBCOPY\n\377\r\n\0 The signature is used to identify files that are malformed through a non-8-bit-clean transfer; it is changed by dropped NULL values, parity changes, newline translation filters, and dropped high bits Integer Layout Field A 32-byte integer constant (0x01020304) in the source's byte order This is to assist an application reading this file format in preventing byte-flipping of multi-byte values Flags Field A 32-bit integer, which is the main storage point for file formatting information Within this field, bits are ordered from (least significant byte, or LSB) to 31 (most significant byte, or MSB) To hold backwards-compatibility formatting information, bits through 15 are reserved Bits 16 through 31 are used to flag critical file formatting information As of 7.1.x, the only bit here that has a definition is bit 16 BIT 16 If bit 16 is set to 1, object IDs are included in the file If bit 16 is set to 0, object IDs are not included Header Extension Length Field This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com A 32-bit integer describing the length, in bytes, of the remainder of the header (not including the header extension length field) In earlier versions, this was set to zero, and the first tuple immediately followed Prev Backend Options for postgres Home Up Next Tuples This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Practical PostgreSQL Prev Appendix D Internal psql Variables The psql client uses a variety of internal variables as special system variables to control aspects of the program A few of the most notable variables are PROMPT1, PROMPT2, and PROMPT3 , which store the prompts for the program While running the program you can set and unset these variables at will using the \set and \unset commands A list of all the special variables psql uses follows: DBNAME This variable holds the name of the database psql is currently connected to This variable is set whenever psql connects to a database, either when starting up or when instructed to connect during program operation ECHO This variable controls what gets displayed on the screen when executing commands from a file To display all contents of a script file on the screen as it is parsed, set this variable to all To display all queries as they are sent to the backend process, set this variable to queries ECHO_HIDDEN This variable, when set to true, displays the queries used by slash commands from within psql Such queries will be displayed before they are sent to the backend To show the queries for slash commands without actually executing them, set ECHO_HIDDEN to noexec ENCODING This variable holds the database's multibyte encoding scheme You must have compiled PostgreSQL to support multibyte encoding; if you did not, this variable will contain SQL_ASCII HISTCONTROL This variable sets methods of controlling the psql history buffer Set this variable to ignorespace if you wish for the history to ignore all lines entered that were preceded by spaces Set it to ignoredups to ignore any entries that matched the previous line entered To ignore both lines beginning with spaces and lines that duplicate, use the value ignoreboth HISTSIZE This variable sets the length of the history buffer; the default length is 500 lines HOST This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com HOST This variable holds the hostname of the database server you are currently connected to This value is set during startup and whenever a database connection occurs IGNOREEOF This variable controls how psql handles EOF characters Normally, when psql receives an EOF character the application terminates This character is usually generated by pressing CTRL-D on the keyboard Setting this option to any non-numeric value will inform psql that you wish to have the EOF character ignored until it is repeated more than 10 times You may alternatively set this variable to a specific number; if you so, psql will ignore that many EOF characters before terminating LASTOID This variable contains the last object identifier (OID) set from an INSERT command, or lo_import() function call LO_TRANSACTION This variable sets the action psql will take during large object operations It may be set to one of the following values: rollback This causes any transaction you are currently working within to be rolled back if you attempt an operation on a large object (or a large object import) For maximum efficiency, large object operations should usually be placed within their own transactions; for this reason, LO_TRANSACTION defaults to rollback commit This causes psql to commit any transaction you were in before you issued a large object operation nothing This causes psql to execute the large object operation within the current transaction ON_ERROR_STOP This variable, when set (to any value), causes psql to terminate the processing of a script that encounters an error (such as incorrect SQL syntax or misuse of a slash command), instead of continuing to process it By default, scripts that have encountered errors continue to be processed by psql PORT This variable holds the port number that you are currently connected to This value is set automatically both when you start the program and when you manually connect to a database from the psql prompt PROMPT1, PROMPT2, PROMPT3 This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com booktown=# SELECT date_trunc('minute', now()); date_trunc -2001-08-31 09:59:00-07 (1 row) booktown=# SELECT date_trunc('hour', now()); date_trunc -2001-08-31 09:00:00-07 (1 row) booktown=# SELECT date_trunc('year', now()); date_trunc -2001-01-01 00:00:00-08 (1 row) extract() extract( k FROM t) extract( k FROM i) The extract() function is the SQL92 equivalent to PostgreSQL's date_part() function, with a slightly modified syntax The SQL syntax for this function uses the FROM keyword, rather than a comma The arguments are similar to those for the date_part() function, though it differs in that its first argument is a SQL keyword, rather than a character string, and should therefore not be quoted Valid values for k are the same as those listed in Table 5-12 Note that the extract() function exists as a SQL92 syntax "alias" for the PostgreSQL date_part() function; for this reason, the output column name from PostgreSQL is, by default, date_ part Examples booktown=# SELECT extract(MINUTE FROM interval('3 days 12 minutes')); date_part 12 (1 row) booktown=# SELECT extract(MONTH FROM now()); date_part (1 row) isfinite() isfinite( t ) isfinite( i ) The isfinite() function accepts one argument, of type timestamp or type interval It returns true if the value passed to it is not found to be an infinite value, which would be one set with either the special constant infinity or invalid (a special timestamp constant only) Example booktown=# SELECT isfinite('now'::timestamp) AS now_is_finite, booktown-# isfinite('infinity'::timestamp) AS infinity, This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com booktown-# isfinite('infinity'::timestamp) AS infinity, booktown-# isfinite('invalid'::timestamp) AS invalid; now_is_finite | infinity | invalid -+ + t | f | f (1 row) now() now() The now() function accepts no arguments, and returns the time and date of when now() is executed by PostgreSQL, in the form of a timestamp value Example booktown=# SELECT now(); now -2001-08-31 10:31:18-07 (1 row) timeofday() timeofday() The timeofday() function accepts no arguments It returns the time and date of when the function is executed by PostgreSQL The timeofday() function is similar in use to the now() function However, the timeofday() function returns a value of the type text This means that it is less flexible to work with, as you cannot use the date_part() or to_char() functions to break down elements of the value without casting it first to another type It can be useful for applications that require a UNIX style timestamp, as well as providing extended precision for the seconds value Example booktown=# SELECT timeofday(); timeofday Fri Aug 31 10:33:00.837338 2001 PDT (1 row) Type Conversion Functions While PostgreSQL is able to explicitly cast between most commonly used data types, some conversions require a function in order to meaningfully translate values Some of PostgreSQL's commonly used type conversion functions are listed in Table 5-13 These are detailed in the following sections Table 5-13 Type conversion functions Function bitfromint4( n ) bittoint4( b ) Description Converts numeric value n to a binary bit string Converts bit string b to its numeric This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com to_char( n , f ) to_char( t , f ) to_date( s , f ) to_number( s , f ) to_timestamp( s , f ) timestamp( d ) Converts bit string b to its numeric decimal representation Converts numeric value n to a character string with format f Converts timestamp t to a character string with format f Converts character string s with date format f to a date value Converts character string s with format f to a numeric value Converts character string s with format f to a timestamp value Returns the date d as a value of type timestamp timestamp( d , t ) Returns a timestamp value derived from date d and time t bitfromint4() bitfromint4( n ) The bitfromint4() function accepts a single argument n of type integer and returns its binary bit string equivalent As explicit casts between binary and integer types not exist, this function is required to transform decimal values to their binary counterparts The returned value is of type bit, and may not exceed 32 bits Therefore, since the integer argument is signed, valid input values are between –2147483648 and 2147483647 Example booktown=# SELECT bitfromint4(16385); bitfromint4 -00000000000000000100000000000001 (1 row) bittoint4() bittoint4( b ) The bittoint4() function is essentially the inverse of the bitfromint4() function; it accepts a single argument b of type bit and returns its decimal numeric value as type integer The bounds of input and output are the reverse of the bitfromint4 function, in that it accepts up to 32 binary digits, and will thus not return more than 2147483647 or less than – 2147483648 as its result value Example booktown=# SELECT bittoint4(B'101010'), booktown-# bittoint4(bitfromint4(99)) AS inverse_example; This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com booktown-# bittoint4(bitfromint4(99)) AS inverse_example; bittoint4 | inverse_example -+ 42 | 99 (1 row) to_char() with numbers to_char( n , f ) The to_char() function, when used with argument n of type numeric and argument f, of type text , formats the numeric value of n to a character string returned as type text The character string f describes the character string format within which to place the value of n The f format string consists of a series of meta-characters, which PostgreSQL translates into the literal values they represent Valid meta-characters that may be used within this format string for a numeric conversion are outlined in Table 5-14 Table 5-14 Numeric conversion formatting characters Character , D G PR SG Description The next sequential digit in the value n The next sequential digit in n, or a leading or trailing zero if more digits are specified by f than are in n; may thus be used to force significant digits to the left or right of a value A decimal point (there can be only one) A comma (there can be several, for separating thousands, millions, etc.) A decimal point (e.g., a period) derived from locale A group separator (e.g., a comma) derived from locale If n is a negative value, placing PR at the end of f surrounds the returned string in angle brackets A plus or minus sign, depending on the value of n MI PL S L RN TH, th V FM A minus sign, if the n is negative A plus sign, if n is positive A plus or minus sign, derived from locale A currency symbol, derived from locale The Roman Numeral characters for numeric values of n between and 3999 The appropriate ordinal suffix for n (e.g., 4th, 2nd) Adds a zero to the right for each following V, effectively shifting up by exponents of ten Sets format to "fill mode," causing leading and This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com trailing zeroes (created by the character, but not 0), and extra whitespace, to be omitted When more digits are specified with the character in the format string than are within the numeric value n, the extra digits will be padded with whitespace When more digits are specified with the character, the extra digits will be padded with zeroes If fewer digits are specified then are necessary to represent the digits to the left of the decimal, the meaning of the conversion becomes ambiguous, as significant digits must be omitted Since it is unclear which digits should be omitted, the to_char() function will enter the # character in place of each specified digit It is therefore important to specify the maximum number of digits that you expect to receive back from the translation You should also use a function such as translate() or one of the trim functions to remove unwanted whitespace from the translation Literal versions of meta-characters may be used within the format string by surrounding them with double quotes Doing this within the format string changes the quoted meta-characters so they are interpreted literally Note that in order to use a literal double-quote within this scheme, two backslashes must prefix the double-quote, as it is essentially twice escaped Note: Any character that is not a meta-character may be safely used in a format string (e.g., the $ symbol) Such characters will appear in the formatted string unchanged Examples booktown=# SELECT to_char(123456789, '999G999G999D99') AS formatted, booktown-# to_char(123456789, '999999999') AS just_digits, booktown-# to_char(123456789, '00999999999') AS with_zeroes; formatted | just_digits | with_zeroes -+ -+ -123,456,789.00 | 123456789 | 00123456789 (1 row) booktown=# SELECT cost * 100 AS cost_to_order, booktown-# to_char(cost * 100, '$99,999.99') AS monetary, booktown-# translate(to_char(cost * 100, '$9,999.99'),' ','') booktown-# AS translated booktown-# FROM stock booktown-# LIMIT 3; cost_to_order | monetary | translated -+ -+ -2900.00 | $ 2,900.00 | $2,900.00 3000.00 | $ 3,000.00 | $3,000.00 1600.00 | $ 1,600.00 | $1,600.00 (3 rows) booktown=# SELECT to_char(1.0, '9th "Place"') AS first, booktown-# to_char(2.2, '9th "Place"') AS second, booktown-# to_char(pi(), '9th "Place"') AS third, booktown-# to_char(10, '99V99th "\\"Place\\""') AS shifted_up; first | second | third | shifted_up + + + 1st Place | 2nd Place | 3rd Place | 1000th "Place" (1 row) Note: Note that as of PostgreSQL v7.1.x, there is a bug in the usage of the RN This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Note: Note that as of PostgreSQL v7.1.x, there is a bug in the usage of the RN Roman Numeral conversion sequence which causes it to return invalid results unless used with the FM character sequence This is scheduled for correction in 7.2, but can be worked around by using the complete FMRN sequence to_char() with timestamps to_char( t , f ) When used with argument t of type timestamp and argument f of type text the to_char function formats the date and time represented by of t to a character string returned as type text As with the numeric functionality of to_char(), the character string f describes the metacharacters which are translated by PostgreSQL into the literal values they represent Valid meta-characters that may be used within this format string for date and time values are outlined in Table 5-15 Table 5-15 Timestamp conversion formatting characters Character HH, HH12 HH24 MI SS SSSS AM, PM, A.M., P.M am, pm, a.m., p.m TZ, tz CC Y, YY, YYY, YYYY, Y,YYY BC, AD, B.C., A.D bc, ad, b.c., a.d MONTH, Month, month MON, Mon, mon MM RN, rn DAY, Day, day Description The hour of day, from to 12 The hour of the day, from to 23 The minute, from to 59 The second, from to 59 The seconds past midnight, from to 86,399 The meridian indicator in uppercase, with optional periods The meridian indicator in lowercase, with optional periods The time zone, in upper or lowercase The two-digit century (not the year divided by 100) The year's last digit, last two digits, last three digits, or last four digits (with optional comma) Year qualifier, in uppercase Year qualifier, in lowercase The full month name, padded on the right with blanks to characters in length, in uppercase, init-capped, or lowercase The abbreviated 3-letter month, in uppercase, init-capped, or lowercase The month number, from to 12 The month in Roman Numerals, from I to XII, in upper or lowercase The full day name, padded on the right to This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com DY, Dy, dy DDD, DD, D W WW IW TH, th fm characters in length, in uppercase, init-capped, or lowercase The abbreviated 3-letter day, in uppercase, initcapped, or lowercase The day of the year, from to 366, day of the month, from to 31, or day of the week, from to (beginning on Sunday) The week of the month, from to (from the 1st day of the month) The week of the year, from to 53 (from the 1st day of the year) The ISO week of the year (from the 1st Thursday of the new year) The appropriate ordinal suffix for the preceding numeric value, upper or lowercase Causes extra padding to be omitted, including whitespace, and extra zeroes The TH suffix and FM prefix must be directly adjacent to the value they are modifying For example, to apply FM to the Day value, the complete sequence would be FMDay (not FM Day) Similarly, to attach the ordinal suffix to the DD day of the month, the complete sequence would be DDTH (not DD TH) Examples booktown=# SELECT to_char(now(), 'HH:MI PM') AS the_time; the_time -05:04 PM (1 row) booktown=# SELECT to_char(now(), 'Dy (Day), Mon (Month)') booktown-# AS abbreviations, booktown-# to_char('yesterday'::timestamp, 'FMMonth FMDDth') booktown-# AS yesterday, booktown-# to_char('yesterday'::timestamp, 'FMDDth FMMonth') booktown-# AS "yesterday UK"; abbreviations | yesterday | yesterday UK + -+ -Sat (Saturday ), Sep (September) | August 31st | 31st August (1 row) booktown=# SELECT isbn, these must be booktown-# to_char(publication, 'FMMonth FMDDth, YYYY') booktown-# AS informal, booktown-# to_char(publication, 'YYYY-MM-DD') AS formal, booktown-# to_char(publication, 'Y,YYY "years" A.D.') booktown-# AS first_published booktown-# FROM editions LIMIT 3; isbn | informal | formal | first_published + + + -039480001X | March 1st, 1957 | 1957-03-01 | 1,957 years A.D 0451160916 | August 1st, 1981 | 1981-08-01 | 1,981 years A.D 0394800753 | March 1st, 1949 | 1949-03-01 | 1,949 years A.D (3 rows) This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com (3 rows) to_date() to_date( s , f ) The to_date() function accepts two arguments s and f, each of type text The argument f describes, using the date-specific meta-characters detailed in Table 5-15, the format of the date described by the string s The result is returned as type date While PostgreSQL can figure out a wide variety of date formats, it cannot support every arbitrary date format The to_date() function insures that, provided the format can be described using the meta- characters from Table 5-14, nearly any date format can be converted to a valid date value Example booktown=# SELECT date('198025thJune') booktown-# AS non_standard_date_format, booktown-# to_date('198025thJune', 'YYYYDDthMonth') booktown-# AS correct_interpretation; non_standard_date_format | correct_interpretation + -2025-08-27 | 1980-06-25 (1 row) to_number() to_number( s , f ) The to_number function operates much like the inverse of the to_char() function for numbers It accepts two arguments s and f, each of type text The character string described by s should have its format described by f, using the same meta-characters shown in Table 514 The result is returned as type numeric Examples booktown=# SELECT to_number('$2,900.00', 'L9G999D99') booktown-# AS monetary; monetary -2900.00 (1 row) booktown=# SELECT to_number('123,456,789.00', '999G999G999D99') booktown-# AS formatted, booktown-# to_number('123456789', '999999999') booktown-# AS just_digits, booktown-# to_number('00123456789', '00999999999') booktown-# AS leading_zeroes; formatted | just_digits | leading_zeroes + -+ -123456789.00 | 123456789 | 123456789 (1 row) to_timestamp() to_timestamp( s , f ) This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com to_timestamp( s , f ) The to_timestamp() function accepts two arguments s and f, each of type text The argument f describes, using the meta-characters detailed in Table 5-15, the format of the date and time described by the string s The result is returned as type date Like to_date(), this function exists primarily as a means to be able to correctly interpret the format of a non-standard date and time string Example booktown=# SELECT timestamp('197825thJuly01:12am') booktown-# AS non_standard_timestamp, booktown-# to_timestamp('197825July01:12am', booktown(# 'YYYYDDFMMonthHH12:MIam') booktown-# AS correct_interpretation; non_standard_timestamp | correct_interpretation + -2025-06-27 01:12:00-07 | 1978-07-25 01:12:00-07 (1 row) Note: The use of the FM modifier can be crucial in making sure the evaluation of values following a month or day name are interpreted correctly, as these names are normally padded to nine characters in length Note that the FM modifier must precede each element which you wish it to apply to, as it is not a "global" modifier timestamp() timestamp( d ) timestamp( d , t ) The timestamp() function accepts either a single argument d of type date, or two arguments d and t, of types date and time , respectively The arguments passed are converted to a value of type timestamp and returned In the former case, the time is assumed to be midnight on the date specified Example booktown=# SELECT timestamp(date('now')) AS today_at_midnight, booktown-# timestamp(date('now'), booktown(# time('now')) AS right_now; today_at_midnight | right_now + -2001-09-01 00:00:00-07 | 2001-09-01 18:04:16-07 (1 row) Aggregate Functions An aggregate function is a special kind of function that operates on several rows of a query at once, returning a single result Such functions are generally only used in queries which make use of the GROUP BY clause to associate rows together by like criteria, though they may be used in queries which only contain aggregate functions in their target list When performing the latter, the aggregate function operates on all selected rows from the result set Table 5-16 provides an overview of PostgreSQL's supported aggregate functions To see a This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Table 5-16 provides an overview of PostgreSQL's supported aggregate functions To see a complete list of aggregate functions, you may use the \da command within psql Table 5-16 Aggregate functions Function avg( expression ) count( expression ) max( expression ) min( expression ) stddev( expression ) sum( expression ) variance( expression ) Description Returns the average of the expression values from all rows in a group Returns the number of values, per each aggregated group of rows, for which expression is not NULL Returns the maximum value of expression in the grouped rows Returns the minimum value of expression in the grouped rows Returns the standard deviation of the values of expression in the grouped rows Returns the sum of the values of expression in the grouped rows Returns the variance of the values of expression in the grouped rows The following sections describe each aggregate function in further detail, including specific information on usage, examples, and valid input data types In each of the functional explanations, the term expression refers to any valid identifier in a result set, or any valid expression operating on such an identifier Aggregate expressions When calling an aggregate function, aggregate expressions are employed to describe an expression from the result set created by the SELECT statement An aggregate expression is similar to an ordinary SQL expression, but may be preceded by either the ALL or the DISTINCT keyword The use of the DISTINCT keyword in an aggregate expression causes only grouped rows with unique values (as described by the expression) to be evaluated by the function Any duplicate rows will be suppressed Similar to the use of the ALL keyword in a SELECT statement, the use of ALL in an aggregate expression has no function other than to make more explicit the request for all grouped rows to be evaluated to the function Example 5-19 demonstrates each of the aggregate expression forms Example 5-19 Using aggregate expressions This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com booktown=# SELECT count(location) AS set_locations, booktown-# count(ALL location) AS all_set_locations, booktown-# count(DISTINCT location) AS unique_locations, booktown-# count(*) AS all_rows booktown-# FROM subjects; set_locations | all_set_locations | unique_locations | all_rows -+ -+ + -15 | 15 | | 16 (1 row) There is one final form of aggregate expression, as demonstrated by the all_rows result column in Example 5-19 When the asterisk (*) symbol is supplied as the aggregate expression, it instructs the aggregate function to evaluate all rows, including rows with values of NULL, which are ordinarily ignored Since the subjects table contains one row with a NULL value in the location column, the counted rows for location differ from those counted for * Warning Rows whose evaluated aggregate expression contain NULL values will not be evaluated by an aggregate function (with the exception of the count() function) avg() avg( expression ) The avg() function accepts an expression describing aggregated values that are either of any numeric type (numeric, bigint, smallint, real, or double precision), or of the interval time type The average, or mean, of the values described by expression in the grouped rows is returned The resultant value is returned as a value of type numeric for expressions of type integer and double precision for expressions of type real All other expression types cause a value of the same data type to be returned Examples booktown=# SELECT avg(cost) AS average_cost, booktown-# avg(retail) AS average_price, booktown-# avg(retail - cost) AS average_profit booktown-# FROM stock; average_cost | average_price | average_profit -+ -+ -24.8235294118 | 30.0088235294 | 5.1852941176 (1 row) booktown=# SELECT avg(cost) AS average_cost, p.name AS publisher booktown-# FROM (stock JOIN editions USING (isbn)) booktown-# JOIN publishers AS p (publisher_id) booktown-# USING (publisher_id) booktown-# GROUP BY p.name; This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com booktown-# GROUP BY p.name; average_cost | publisher -+ 26.5000000000 | Ace Books 19.0000000000 | Books of Wonder 26.5000000000 | Doubleday 25.0000000000 | HarperCollins 18.0000000000 | Henry Holt & Company, Inc 23.0000000000 | Kids Can Press 23.0000000000 | Mojo Press 20.0000000000 | Penguin 23.0000000000 | Random House 26.5000000000 | Roc 26.0000000000 | Watson-Guptill Publications (11 rows) count() count( expression ) The count() function returns the number of values in a set of aggregated rows where the expression is not NULL The count() is not restricted as to the data type described by expression It is important to understand that the count() function only counts values which are not NULL As a result, it is important to use an expression whose value will not be returned NULL in order for the expression to be meaningful to the counted results You may pass the asterisk (*) character to count() in order to simply count all rows in an aggregation (including rows with NULL values) Examples booktown=# SELECT count(*) FROM editions; count 17 (1 row) booktown=# SELECT count(isbn), p.name booktown-# FROM editions JOIN publishers AS p (publisher_id) booktown-# USING (publisher_id) booktown-# GROUP BY p.name booktown-# ORDER BY count DESC; count | name -+ | Random House | Ace Books | Doubleday | Roc | Books of Wonder | HarperCollins | Henry Holt & Company, Inc | Kids Can Press | Mojo Press | O'Reilly & Associates | Penguin | Watson-Guptill Publications (12 rows) max() max( expression ) This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com max( expression ) The max() function returns the maximum found value described by expression in a set of aggregated rows It accepts an expression that may represent any numeric, string, date, or time data type The maximum is returned as a value of the same data type as the expression Examples booktown=# SELECT max(cost), max(retail) FROM stock; max | max -+ 36.00 | 46.95 (1 row) booktown=# SELECT max(retail), p.name booktown-# FROM (stock NATURAL JOIN editions) booktown-# JOIN publishers AS p (publisher_id) booktown-# USING (publisher_id) booktown-# GROUP BY p.name booktown-# ORDER BY max DESC; max | name -+ 46.95 | Roc 45.95 | Ace Books 36.95 | Doubleday 32.95 | Random House 28.95 | HarperCollins 28.95 | Watson-Guptill Publications 24.95 | Mojo Press 24.95 | Penguin 23.95 | Henry Holt & Company, Inc 23.95 | Kids Can Press 21.95 | Books of Wonder (11 rows) min() min( expression ) The min() function returns the minimum found value described by expression in a set of aggregated rows It accepts an expression which may represent any numeric, string, date, or time data type The minimum is returned as a value of the same data type as the expression Examples booktown=# SELECT min(cost), min(retail) FROM stock; | -+ 16.00 | 16.95 (1 row) booktown=# SELECT min(retail), p.name booktown-# FROM (stock NATURAL JOIN editions) booktown-# JOIN publishers AS p (publisher_id) booktown-# USING (publisher_id) booktown-# GROUP BY p.name booktown-# ORDER BY ASC; This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com booktown-# ORDER BY ASC; | name -+ 16.95 | Random House 21.95 | Ace Books 21.95 | Books of Wonder 22.95 | Roc 23.95 | Henry Holt & Company, Inc 23.95 | Kids Can Press 24.95 | Mojo Press 24.95 | Penguin 28.95 | Doubleday 28.95 | HarperCollins 28.95 | Watson-Guptill Publications (11 rows) stddev() stddev( expression ) The stddev() function accepts an expression describing values of any numeric type (numeric, bigint , smallint , real , or double precision ), and returns the standard deviation of the values within the aggregated rows The resultant value is returned as double precision for an expression describing floating point values, and numeric for all other types Examples booktown=# SELECT stddev(retail) FROM stock; stddev -8.46 (1 row) booktown=# SELECT stddev(retail), p.name booktown-# FROM (stock NATURAL JOIN editions) booktown-# JOIN publishers AS p ON (publisher_id = p.id) booktown-# GROUP BY p.name booktown-# ORDER BY stddev DESC booktown-# LIMIT 4; stddev | name + -16.97 | Ace Books 16.97 | Roc 8.02 | Random House 5.66 | Doubleday (4 rows) sum() sum( expression ) The sum() function accepts an expression describing values of any numeric type (numeric, bigint , smallint , real , or double precision ), and returns the sum of the values within the aggregated rows The returned value is of the type numeric when operating on values of type integer and double precision when operating on values of type real The result is returned as the same data type as the values described by expression for all other data types Examples booktown=# SELECT sum(stock) FROM stock; This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com booktown=# SELECT sum(stock) FROM stock; sum 508 (1 row) booktown=# SELECT sum(stock), s.subject booktown-# FROM ((stock NATURAL JOIN editions) booktown(# JOIN books ON (books.id = book_id)) booktown-# JOIN subjects AS s booktown-# ON (books.subject_id = s.id) booktown-# GROUP BY s.subject booktown-# ORDER BY sum DESC; sum | subject -+ -189 | Horror 166 | Science Fiction 91 | Children's Books 28 | Drama 18 | Classics 16 | Arts (6 rows) variance() variance( expression ) The variance() function accepts an expression describing values of any numeric type (numeric, bigint, smallint, real, or double precision) and returns the variance of the values within the aggregated rows The variance is equivalent to the stddev() squared The resultant value is returned as double precision for an expression describing floating-point values, and numeric for all other types Examples booktown=# SELECT variance(retail) FROM stock; variance -71.60 (1 row) booktown=# SELECT variance(retail), p.name booktown-# FROM (stock NATURAL JOIN editions) booktown-# JOIN publishers AS p booktown-# ON (editions.publisher_id = p.id) booktown-# GROUP BY p.name booktown-# ORDER BY variance DESC booktown-# LIMIT 4; variance | name + 288.00 | Ace Books 288.00 | Roc 64.33 | Random House 32.00 | Doubleday (4 rows) Prev Operators and Functions Home Up Next PostgreSQL Clients ... Options for postgres This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Practical PostgreSQL Prev Next Appendix B Backend Options for postgres The postgres... What is PostgreSQL? Open Source Free Version PostgreSQL Feature Set Where to Proceed from Here Installing PostgreSQL Preparing for Installation 10 Steps to Installing PostgreSQL II Using PostgreSQL... tables to be modified -p database The postmaster parameter, indicating that this postgres instance was started by postmaster connecting to database This causes postgres to make different decisions

Ngày đăng: 26/03/2019, 11:24

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan