From: Peter Eisentraut Date: Thu, 14 Dec 2000 22:30:56 +0000 (+0000) Subject: Merge functions and operators chapters. Lots of updates. X-Git-Tag: REL7_1_BETA2~178 X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=c3641483c31112409af28800385455d36108629d;p=postgresql Merge functions and operators chapters. Lots of updates. --- diff --git a/doc/src/sgml/Makefile b/doc/src/sgml/Makefile index acf6afb14a..3d024e01f2 100644 --- a/doc/src/sgml/Makefile +++ b/doc/src/sgml/Makefile @@ -8,7 +8,7 @@ # # # IDENTIFICATION -# $Header: /cvsroot/pgsql/doc/src/sgml/Makefile,v 1.26 2000/11/24 17:44:21 petere Exp $ +# $Header: /cvsroot/pgsql/doc/src/sgml/Makefile,v 1.27 2000/12/14 22:30:56 petere Exp $ # #---------------------------------------------------------------------------- @@ -16,6 +16,7 @@ subdir = doc/src/sgml top_builddir = ../../.. include $(top_builddir)/src/Makefile.global +.SECONDARY: ifndef DOCBOOKSTYLE DOCBOOKSTYLE = /home/projects/pgsql/developers/thomas/db143.d/docbook diff --git a/doc/src/sgml/datatype.sgml b/doc/src/sgml/datatype.sgml index 892b827b3b..6afe6cdb5a 100644 --- a/doc/src/sgml/datatype.sgml +++ b/doc/src/sgml/datatype.sgml @@ -1,5 +1,5 @@ @@ -349,8 +349,7 @@ $Header: /cvsroot/pgsql/doc/src/sgml/datatype.sgml,v 1.43 2000/12/03 14:47:18 th The numeric types have a full set of corresponding arithmetic operators and - functions. Refer to - and for more information. + functions. Refer to for more information. diff --git a/doc/src/sgml/filelist.sgml b/doc/src/sgml/filelist.sgml index 051a432d9f..98b5014ce0 100644 --- a/doc/src/sgml/filelist.sgml +++ b/doc/src/sgml/filelist.sgml @@ -1,4 +1,4 @@ - + @@ -26,7 +26,6 @@ - diff --git a/doc/src/sgml/func.sgml b/doc/src/sgml/func.sgml index f028045b4b..5b3012625e 100644 --- a/doc/src/sgml/func.sgml +++ b/doc/src/sgml/func.sgml @@ -1,635 +1,1173 @@ - - Functions - - + + + + Functions and Operators + + + Postgres provides a large number of + functions and operators for the built-in data types. Users can also + define their own functions and operators, as described in the + Programmer's Guide. The + psql commands \df and + \do can be used to show the list of all actually + available function and operators, respectively. + + + + If you are concerned about portability then take note that most of + the functions and operators described in this chapter, with the + exception of the most trivial arithmetic and comparison operators + and some explicitly marked functions, are not specified by the SQL + standard. However, many other RDBMS packages provide a lot of the + same or similar functions, and some of the ones provided in + Postgres have in fact been inspired by + other implementations. + + + + Comparison Operators + + + Comparison Operators + + + + Operator + Description + + + + + + < + less than + + + + > + greater than + + + + <= + less than or equal to + + + + >= + greater than or equal to + + + + = + equal + + + + <> or != + not equal + + + +
+ + - Describes the built-in functions available - in Postgres. + The != operator is converted to + <> in the parser stage. It is not + possible to implement != and + <> operators that do different things. -
+ + + + Comparison operators are available for all data types where this + makes sense. All comparison operators are binary operators that + return boolean values; expressions like 1 < 2 < + 3 are not valid (because there is no + < operator to compare a boolean with + 3). + + + + + + Mathematical Functions and Operators + + + Mathematical Operators + + + + + Name + Description + Example + Result + + + + + + + + Addition + 2 + 3 + 5 + + + + - + Subtraction + 2 - 3 + -1 + + + + * + Multiplication + 2 * 3 + 6 + + + + / + Division (integer division truncates results) + 4 / 2 + 2 + + + + % + Modulo (remainder) + 5 % 4 + 1 + + + + ^ + Exponentiation + 2.0 ^ 3.0 + 8.0 + + + + |/ + Square root + |/ 25.0 + 5.0 + + + + ||/ + Cube root + ||/ 27.0 + 3 + + + + ! + Factorial + 5 ! + 120 + + + + !! + Factorial (left operator) + !! 5 + 120 + + + + @ + Absolute value + @ -5.0 + 5.0 + + + +
+ + + + + Mathematical Functions + + + + Function + Return Type + Description + Example + Result + + + + + + abs(x) + (same as argument type) + absolute value + abs(-17.4) + 17.4 + + + + cbrt(double precision) + double precision + cube root + cbrt(27.0) + 9.0 + + + + ceil(numeric) + numeric + smallest integer not less than argument + ceil(-42.8) + -42 + + + + degrees(double precision) + double precision + convert radians to degrees + degrees(0.5) + 28.6478897565412 + + + + exp(double precision) + double precision + exponential function + exp(1.0) + 2.71828182845905 + + + + floor(numeric) + numeric + largest integer not greater than argument + floor(-42.8) + 43 + + + + ln(double precision) + double precision + natural logarithm + ln(2.0) + 0.693147180559945 + + + + log(double precision) + double precision + base 10 logarithm + log(100.0) + 2.0 + + + + log(base numeric, x numeric) + numeric + logarithm to specified base + log(2.0, 64.0) + 6.0 + + + + mod(y, x) + (same as argument types) + remainder (modulo) of the division y/x + mod(9,4) + 1 + + + + pi() + double precision + Pi constant + pi() + 3.14159265358979 + + + + pow(double precision, double precision) + double precision + raise a number to the specified exponent + pow(9.0, 3.0) + 729.0 + + + + radians(double precision) + double precision + convert degrees to radians + radians(45.0) + 0.785398163397448 + + + + random() + double precision + a pseudo-random value between 0.0 to 1.0 + random() + + + + + round(double precision) + double precision + round to nearest integer + round(42.4) + 42 + + + + round(value numeric, scale integer) + numeric + round to specified number of decimal places + round(42.4382, 2) + 42.44 + + + + sqrt(double precision) + double precision + square root + sqrt(2.0) + 1.4142135623731 + + + + trunc(double precision) + double precision + truncate (toward zero) + trunc(42.8) + 42 + + + + trunc(value numeric, scale integer) + numeric + truncate to specified number of decimal places + round(42.4382, 2) + 42.43 + + + + +
+ + + The functions exp, ln, + log, pow, + round (1 argument), sqrt, + and trunc (1 argument) are also available for + the type numeric in place of double + precision. Many of these functions are implemented on top + of the host system's C library and behavior in boundary cases could + therefore vary depending on the operating system. + + + + Trigonometric Functions + + + + + Function + Description + + + + + + acos(x) + inverse cosine + + + + asin(x) + inverse sine + + + + atan(x) + inverse tangent + + + + atan2(x, y) + inverse tangent of y/x + + + + cos(x) + cosine + + + + cot(x) + cotangent + + + + sin(x) + sine + + + + tan(x) + tangent + + + +
+ + + All trigonometric functions have arguments and return values of + type double precision. + + +
+ + + + String Functions and Operators + + + This section describes functions and operators for examining and + manipulating string values. Strings in this context include values + of all the types CHARACTER, CHARACTER + VARYING, and TEXT. Unless otherwise noted, all + of the functions listed below work on all of these types, but be + wary of potential effects of the automatic padding when using the + CHARACTER type. Generally the functions described + here also work on data of non-string types by converting that data + to a string representation first. + + + + SQL defines some string functions with a special syntax where + certain keywords rather than commas are used to separate the + arguments. Details are in . + These functions are also implemented using the regular syntax for + function invocation. (See .) + + + + <acronym>SQL</acronym> String Functions and Operators + + + + Function + Return Type + Description + Example + Result + + + + + + string || string + text + string concatenation + 'Postgre' || 'SQL' + PostgreSQL + + + + char_length(string) or character_length(string) + integer + length of string + char_length('jose') + 4 + + + + lower(string) + text + Convert string to lower case. + lower('TOM') + tom + + + + octet_length(string) + integer + number of bytes in string + octet_length('jose') + 4 + + + + position(substring in string) + integer + location of specified substring + position('om' in 'Thomas') + 3 + + + + substring(string from integer for integer) + text + extract substring + substring('Thomas' from 2 for 3) + oma + + + + + trim(leading | trailing | both + characters from + string) + + text + + Removes the longest string containing only the + characters (a space by default) from the + beginning/end/both ends of the string. + + trim(both 'x' from 'xTomx') + Tom + + + + upper(string) + text + Convert string to upper case. + upper('tom') + TOM + + + +
- Many data types have functions available for conversion to other related types. - In addition, there are some type-specific functions. Some functions are also - available through operators and may be documented as operators only. + Additional string manipulation functions are available and are + listed below. Some of them are used internally to implement the + SQL string functions listed above. - - SQL Functions + + Other String Functions + + + + Function + Return type + Description + Example + Result + + + + + + ascii(text) + integer + Returns the ASCII code of the first character of the argument. + ascii('x') + 120 + + + + btrim(string text, trim text) + text + + Remove (trim) the longest string consisting only of characters + in trim from the start and end of + string. + + btrim('xyxtrimyyx','xy') + trim + + + + chr(integer) + text + Returns the character with the given ASCII code. + chr(65) + A + + + + initcap(text) + text + Converts first letter of each word (whitespace separated) to upper case. + initcap('hello thomas') + Hello Thomas + + + + + lpad(string text, + length integer + , fill text) + + text + + Fills up the string to length + length by prepending the characters + fill (a space by default). If the + string is already longer than + length then it is truncated (on the + right). + + lpad('hi', 5, 'xy') + xyxhi + + + + ltrim(string text, trim text) + text + + Removes the longest string containing only characters from + trim from the start of the string. + + ltrim('zzzytrim','xyz') + trim + + + + repeat(text, integer) + text + Repeat text a number of times. + repeat('Pg', 4) + PgPgPgPg + + + + + rpad(string text, + length integer + , fill text) + + text + + Fills up the string to length + length by appending the characters + fill (a space by default). If the + string is already longer than + length then it is truncated. + + rpad('hi', 5, 'xy') + hixyx + + + + rtrim(string text, trim text) + text + + Removes the longest string containing only characters from + trim from the end of the string. + + rtrim('trimxxxx','x') + trim + + + + strpos(string, substring) + text + + Locates specified substring. (same as + position(substring in + string), but note the reversed + argument order) + + strpos('high','ig') + + + + substr(string, from , count) + text + + Extracts specified substring. (same as substring(string from from for count)) + + substr('alphabet', 3, 2) + ph + + + + to_ascii(text , encoding) + text + Converts text from multibyte encoding to ASCII. + to_ascii('Karel') + + + + + + translate(string text, + from text, + to text) + + text + + Any character in string that matches a + character in the from set is replaced by + the corresponding character in the to + set. + + translate('12345', '14', 'ax') + a23x5 + + + + +
+ + + The to_ascii function supports conversion from + LATIN1, LATIN2, WIN1250 (CP1250) only. + +
+ + + + Pattern Matching + + + There are two separate approaches to pattern matching provided by + Postgres: The SQL + LIKE operator and + POSIX-style regular expressions. + + - SQL functions are constructs - defined by the SQL92 standard which have - function-like syntax but which can not be implemented as simple - functions. + If you have pattern matching needs that go beyond this, or want to + make pattern-driven substitutions or translations, consider + writing a user-defined function in Perl or Tcl. + + + + Pattern Matching with <function>LIKE</function> + + +string LIKE pattern ESCAPE escape-character +string NOT LIKE pattern ESCAPE escape-character + - - SQL Functions - - - - Function - Returns - Description - Example - - - - - COALESCE(list) - non-NULL - return first non-NULL value in list - COALESCE(rle, c2 + 5, 0) - - - NULLIF(input,value) - input or NULL - return NULL if - input = - value, - else input - - NULLIF(c1, 'N/A') - - - CASE WHEN expr THEN expr [...] ELSE expr END - expr - return expression for first true WHEN clause - CASE WHEN c1 = 1 THEN 'match' ELSE 'no match' END - - - -
+ Every pattern defines a set of strings. + The LIKE expression returns true if the + string is contained in the set of + strings represented by pattern. (As + expected, the NOT LIKE expression returns + false if LIKE returns true, and vice versa. + An equivalent expression is NOT + (string LIKE + pattern).)
-
- - Mathematical Functions + + If pattern does not contain percent + signs or underscore then the pattern only represents the string + itself; in that case LIKE acts like the + equals operator. An underscore (_) in + pattern stands for (matches) any single + character, a percent sign (%) matches zero or + more characters. + + + + + Some examples: + +'abc' LIKE 'abc' true +'abc' LIKE 'a%' true +'abc' LIKE '_b_' true +'abc' LIKE 'c' false + + + - - Mathematical Functions - - - - Function - Returns - Description - Example - - - - - abs(float8) - float8 - absolute value - abs(-17.4) - - - degrees(float8) - float8 - radians to degrees - degrees(0.5) - - - exp(float8) - float8 - raise e to the specified exponent - exp(2.0) - - - ln(float8) - float8 - natural logarithm - ln(2.0) - - - log(float8) - float8 - base 10 logarithm - log(2.0) - - - pi() - float8 - fundamental constant - pi() - - - pow(float8,float8) - float8 - raise a number to the specified exponent - pow(2.0, 16.0) - - - radians(float8) - float8 - degrees to radians - radians(45.0) - - - round(float8) - float8 - round to nearest integer - round(42.4) - - - sqrt(float8) - float8 - square root - sqrt(2.0) - - - cbrt(float8) - float8 - cube root - cbrt(27.0) - - - trunc(float8) - float8 - truncate (towards zero) - trunc(42.4) - - - float(int) - float8 - convert integer to floating point - float(2) - - - float4(int) - float4 - convert integer to floating point - float4(2) - - - integer(float) - int - convert floating point to integer - integer(2.0) - - - random() - float8 - random value in the range 0.0 to 1.0 - random() - - - setseed(float8) - int - set seed for subsequent random() calls - setseed(0.54823) - - - -
+ LIKE pattern matches always cover the entire + string. On order to match a pattern anywhere within a string, the + pattern must therefore start and end with a percent sign.
- Most of the functions listed for FLOAT8 are also available for - type NUMERIC. + In order to match a literal underscore or percent sign, the + respective character in pattern must be + preceded by the active escape character. The default escape + character is the backslash but a different one may be selected by + using the ESCAPE clause. When using the + backslash as escape character in literal strings it must be + doubled, because the backslash already has a special meaning in + string literals. - - Transcendental Mathematical Functions - - - - Function - Returns - Description - Example - - - - - acos(float8) - float8 - arccosine - acos(10.0) - - - asin(float8) - float8 - arcsine - asin(10.0) - - - atan(float8) - float8 - arctangent - atan(10.0) - - - atan2(float8,float8) - float8 - arctangent - atan2(10.0,20.0) - - - cos(float8) - float8 - cosine - cos(0.4) - - - cot(float8) - float8 - cotangent - cot(20.0) - - - sin(float8) - float8 - sine - cos(0.4) - - - tan(float8) - float8 - tangent - tan(0.4) - - - -
+ The keyword ILIKE can be used instead of + LIKE to make the match case insensitive according + to the active locale. This is a + Postgres extension.
-
+ + The operator ~~ is equivalent to + LIKE, ~~* corresponds to + ILIKE. Finally, there are also + !~~ and !~~* operators to + represent NOT LIKE and NOT + ILIKE. All of these are also + Postgres-specific. + + - - String Functions + + + POSIX Regular Expressions - SQL92 defines string functions with specific syntax. Some of these - are implemented using other Postgres functions. - The supported string types for SQL92 are - char, varchar, and text. + POSIX regular expressions provide a more powerful means for + pattern matching than the LIKE function. + Many Unix tools such as egrep, + sed, or awk use a pattern + matching language that is similar to the one described here. - - <acronym>SQL92</acronym> String Functions - - - - Function - Returns - Description - Example - - - - - char_length(string) - int4 - length of string - char_length('jose') - - - character_length(string) - int4 - length of string - char_length('jose') - - - lower(string) - string - convert string to lower case - lower('TOM') - - - octet_length(string) - int4 - storage length of string - octet_length('jose') - - - position(string in string) - int4 - location of specified substring - position('o' in 'Tom') - - - substring(string [from int] [for int]) - string - extract specified substring - substring('Tom' from 2 for 2) - - - trim([leading|trailing|both] [string] from string) - string - trim characters from string - trim(both 'x' from 'xTomx') - - - upper(text) - text - convert text to upper case - upper('tom') - - - -
+ A regular expression is a character sequence that is an + abbreviated definition of a set of strings (a regular + set). A string is said to match a regular expression + if it is a member of the regular set described by the regular + expression. Unlike the LIKE operator, a + regular expression also matches anywhere within a string, unless + the regular expression is explicitly anchored to the beginning or + end of the string.
+ + Regular Expression Match Operators + + + + + Operator + Description + Example + + + + + + ~ + Matches regular expression, case sensitive + 'thomas' ~ '.*thomas.*' + + + ~* + Matches regular expression, case insensitive + 'thomas' ~* '.*Thomas.*' + + + !~ + Does not match regular expression, case sensitive + 'thomas' !~ '.*Thomas.*' + + + !~* + Does not match regular expression, case insensitive + 'thomas' !~* '.*vadim.*' + + + +
+ + + - Many additional string functions are available for text, varchar(), and char() types. - Some are used internally to implement the SQL92 string functions listed above. + Regular expressions (REs), as defined in POSIX + 1003.2, come in two forms: modern REs (roughly those of + egrep; 1003.2 calls these + extended REs) and obsolete REs (roughly those of + ed; 1003.2 basic REs). Obsolete + REs are not available in Postgres. - - String Functions - - - - Function - Returns - Description - Example - - - - - ascii(text) - int - returns the decimal representation of the first character from text - ascii('x') - - - btrim(text,set) - text - both (left and right) trim characters from text - btrim('xxxtrimxxx','x') - - - char(text) - char - convert text to char type - char('text string') - - - char(varchar) - char - convert varchar to char type - char(varchar 'varchar string') - - - chr(int) - text - returns the character having the binary equivalent to int - chr(65) - - - initcap(text) - text - first letter of each word to upper case - initcap('thomas') - - - lpad(text,int,text) - text - left pad string to specified length - lpad('hi',4,'??') - - - ltrim(text,text) - text - left trim characters from text - ltrim('xxxxtrim','x') - - - repeat(text,int) - text - repeat text by int - repeat('Pg', 4) - - - rpad(text,int,text) - text - right pad string to specified length - rpad('hi',4,'x') - - - rtrim(text,text) - text - right trim characters from text - rtrim('trimxxxx','x') - - - substr(text,int[,int]) - text - extract specified substring - substr('hi there',3,5) - - - text(char) - text - convert char to text type - text('char string') - - - text(varchar) - text - convert varchar to text type - text(varchar 'varchar string') - - - strpos(text,text) - text - locate specified substring - strpos('high','ig') - - - to_ascii(text [,name|int]) - text - convert text from multibyte encoding to ASCII - to_ascii('Karel') - - - translate(text,from,to) - text - convert character in string - translate('12345', '1', 'a') - - - varchar(char) - varchar - convert char to varchar type - varchar('char string') - - - varchar(text) - varchar - convert text to varchar type - varchar('text string') - - - -
+ A (modern) RE is one or more non-empty + branches, separated by + |. It matches anything that matches one of the + branches.
- Most functions explicitly defined for text will work for char() and varchar() arguments. + A branch is one or more pieces, + concatenated. It matches a match for the first, followed by a + match for the second, etc. + - The to_ascii() support conversion from LATIN1, LATIN2, WIN1250 (CP1250) only. + A piece is an atom possibly followed by a + single *, +, + ?, or bound. An atom + followed by * matches a sequence of 0 or more + matches of the atom. An atom followed by + + matches a sequence of 1 or more matches of the atom. An atom + followed by ? matches a sequence of 0 or 1 + matches of the atom. -
- - Date/Time Functions + + A bound is { followed by + an unsigned decimal integer, possibly followed by + , possibly followed by another unsigned decimal + integer, always followed by }. The integers + must lie between 0 and RE_DUP_MAX (255) + inclusive, and if there are two of them, the first may not exceed + the second. An atom followed by a bound containing one integer + i and no comma matches a sequence of + exactly i matches of the atom. An atom + followed by a bound containing one integer + i and a comma matches a sequence of + i or more matches of the atom. An atom + followed by a bound containing two integers + i and j + matches a sequence of i through + j (inclusive) matches of the atom. + + + + + A repetition operator (?, + *, +, or bounds) cannot + follow another repetition operator. A repetition operator cannot + begin an expression or subexpression or follow + ^ or |. + + - The date/time functions provide a powerful set of tools - for manipulating various date/time types. + An atom is a regular expression enclosed in + () (matching a match for the regular + expression), an empty set of () (matching the + null string), a bracket expression (see + below), . (matching any single character), + ^ (matching the null string at the beginning of + a line), $ (matching the null string at the end + of a line), a \ followed by one of the + characters ^.[$()|*+?{\ (matching that + character taken as an ordinary character), a \ + followed by any other character (matching that character taken as + an ordinary character, as if the \ had not been + present), or a single character with no other significance + (matching that character). A { followed by a + character other than a digit is an ordinary character, not the + beginning of a bound. It is illegal to end an RE with + \. - - Date/Time Functions - - - - Function - Returns - Description - Example - - - - - abstime(timestamp) - abstime - convert to abstime - abstime(timestamp 'now') - - - age(timestamp) - interval - preserve months and years - age(timestamp '1957-06-13') - - - age(timestamp,timestamp) - interval - preserve months and years - age('now', timestamp '1957-06-13') - - - date_part(text,timestamp) - float8 - portion of date - date_part('dow',timestamp 'now') - - - date_part(text,interval) - float8 - portion of time - date_part('hour',interval '4 hrs 3 mins') - - - date_trunc(text,timestamp) - timestamp - truncate date - date_trunc('month',abstime 'now') - - - interval(reltime) - interval - convert to interval - interval(reltime '4 hours') - - - isfinite(timestamp) - bool - a finite time? - isfinite(timestamp 'now') - - - isfinite(interval) - bool - a finite time? - isfinite(interval '4 hrs') - - - reltime(interval) - reltime - convert to reltime - reltime(interval '4 hrs') - - - timestamp(date) - timestamp - convert to timestamp - timestamp(date 'today') - - - timestamp(date,time) - timestamp - convert to timestamp - timestamp(timestamp '1998-02-24',time '23:07'); - - - to_char(timestamp,text) - text - convert to string - to_char(timestamp '1998-02-24','DD'); - - - -
+ A bracket expression is a list of + characters enclosed in []. It normally matches + any single character from the list (but see below). If the list + begins with ^, it matches any single character + (but see below) not from the rest of the list. If two characters + in the list are separated by -, this is + shorthand for the full range of characters between those two + (inclusive) in the collating sequence, + e.g. [0-9] in ASCII matches + any decimal digit. It is illegal for two ranges to share an + endpoint, e.g. a-c-e. Ranges are very + collating-sequence-dependent, and portable programs should avoid + relying on them.
- For the - date_part and date_trunc - functions, arguments can be - `year', `month', - `day', `hour', - `minute', and `second', - as well as the more specialized quantities - `decade', `century', - `millennium', `millisecond', - and `microsecond'. - date_part allows `dow' - to return day of week, 'week' to return the - ISO-defined week of year, and `epoch' to return - seconds since 1970 (for timestamp) - or 'epoch' to return total elapsed seconds - (for interval). + To include a literal ] in the list, make it the + first character (following a possible ^). To + include a literal -, make it the first or last + character, or the second endpoint of a range. To use a literal + - as the first endpoint of a range, enclose it + in [. and .] to make it a + collating element (see below). With the exception of these and + some combinations using [ (see next + paragraphs), all other special characters, including + \, lose their special significance within a + bracket expression. + + + + Within a bracket expression, a collating element (a character, a + multi-character sequence that collates as if it were a single + character, or a collating-sequence name for either) enclosed in + [. and .] stands for the + sequence of characters of that collating element. The sequence is + a single element of the bracket expression's list. A bracket + expression containing a multi-character collating element can thus + match more than one character, e.g. if the collating sequence + includes a ch collating element, then the RE + [[.ch.]]*c matches the first five characters of + chchcc. + + + + Within a bracket expression, a collating element enclosed in + [= and =] is an equivalence + class, standing for the sequences of characters of all collating + elements equivalent to that one, including itself. (If there are + no other equivalent collating elements, the treatment is as if the + enclosing delimiters were [. and + .].) For example, if o and + ^ are the members of an equivalence class, then + [[=o=]], [[=^=]], and + [o^] are all synonymous. An equivalence class + may not be an endpoint of a range. + + + + Within a bracket expression, the name of a character class + enclosed in [: and :] stands + for the list of all characters belonging to that class. Standard + character class names are: alnum, + alpha, blank, + cntrl, digit, + graph, lower, + print, punct, + space, upper, + xdigit. These stand for the character classes + defined in + ctype3. + A locale may provide others. A character class may not be used as + an endpoint of a range. + + + + There are two special cases of bracket expressions: the bracket + expressions [[:<:]] and + [[:>:]] match the null string at the beginning + and end of a word respectively. A word is defined as a sequence + of word characters which is neither preceded nor followed by word + characters. A word character is an alnum character (as defined by + ctype3) + or an underscore. This is an extension, compatible with but not + specified by POSIX 1003.2, and should be used with caution in + software intended to be portable to other systems. + + + + In the event that an RE could match more than one substring of a + given string, the RE matches the one starting earliest in the + string. If the RE could match more than one substring starting at + that point, it matches the longest. Subexpressions also match the + longest possible substrings, subject to the constraint that the + whole match be as long as possible, with subexpressions starting + earlier in the RE taking priority over ones starting later. Note + that higher-level subexpressions thus take priority over their + lower-level component subexpressions. + + + + Match lengths are measured in characters, not collating + elements. A null string is considered longer than no match at + all. For example, bb* matches the three middle + characters of abbbc, + (wee|week)(knights|nights) matches all ten + characters of weeknights, when + (.*).* is matched against + abc the parenthesized subexpression matches all + three characters, and when (a*)* is matched + against bc both the whole RE and the + parenthesized subexpression match the null string. + + + + If case-independent matching is specified, the effect is much as + if all case distinctions had vanished from the alphabet. When an + alphabetic that exists in multiple cases appears as an ordinary + character outside a bracket expression, it is effectively + transformed into a bracket expression containing both cases, + e.g. x becomes [xX]. When + it appears inside a bracket expression, all case counterparts of + it are added to the bracket expression, so that (e.g.) + [x] becomes [xX] and + [^x] becomes [^xX]. + + + + There is no particular limit on the length of REs, except insofar + as memory is limited. Memory usage is approximately linear in RE + size, and largely insensitive to RE complexity, except for bounded + repetitions. Bounded repetitions are implemented by macro + expansion, which is costly in time and space if counts are large + or bounded repetitions are nested. An RE like, say, + ((((a{1,100}){1,100}){1,100}){1,100}){1,100} + will (eventually) run almost any existing machine out of swap + space.This was written in 1994, mind you. The + numbers have probably changed, but the problem + persists. -
+ + - - + + + + Formatting Functions Author - Written by - Karel Zak - on 2000-01-24. + Written by Karel Zak (zakkr@zf.jcu.cz) on 2000-01-24 + - The Postgres - formatting functions provide a powerful set of tools for converting - various datetypes (date/time, int, float, numeric) to formatted strings - and for converting from formatted strings to specific datetypes. - - - - The second argument for all formatting functions is a template to - be used for the conversion. - - + The Postgres formatting functions + provide a powerful set of tools for converting various data types + (date/time, integer, floating point, numeric) to formatted strings + and for converting from formatted strings to specific datetypes. + These functions all follow a common calling convention: The first + argument is the value to be formatted and the second argument is a + template that defines the output format. @@ -837,7 +1375,7 @@ IW - ISO week number of year + ISO week number of year (The first Thursday of the new year is in week 1.) CC @@ -853,19 +1391,19 @@ RM - month in Roman Numerals (I-XII; I=JAN) - upper case + month in Roman Numerals (I-XII; I=January) - upper case rm - month in Roman Numerals (I-XII; I=JAN) - lower case + month in Roman Numerals (I-XII; I=January) - lower case TZ - timezone string - upper case (not supported in the to_timestamp()) + timezone string - upper case tz - timezone string - lower case (not supported in the to_timestamp()) + timezone string - lower case @@ -875,7 +1413,7 @@ All templates allow the use of prefix and suffix modifiers. Modifiers are always valid for use in templates. The prefix - 'FX' is a global modifier only. + FX is a global modifier only. @@ -938,40 +1476,43 @@ - Backslash ("\") must be specified with a double backslash - ("\\"); for example '\\HH\\MI\\SS'. + If a backslash (\) is desired + in a string constant, a double backslash + (\\) must be entered; for + example '\\HH\\MI\\SS'. This is true for + any string constant in Postgres. - A double quote (") between - quotation marks is skipped and is not parsed. If you want to - write a double quote to output you must preceed it with a - double backslash ('\\"), for example - '\\"YYYY Month\\"'. + Ordinary text is allowed in to_char + templates but any string between double quotes is guaranteed + that it will not be interpreted as a template keyword and it is + also processed faster. (Example: '"Hello Year: + "YYYY'). - to_char supports text without a leading - double quote but any string - between a quotation marks is rapidly handled and you are - guaranteed that it will not be interpreted as a template - keyword (example: '"Hello Year: "YYYY'). + A double quote (") between + quotation marks is skipped and is not parsed. If you want to + have a double quote in the output you must preceed it with a + double backslash, for example '\\"YYYY + Month\\"'. YYYY conversion from string to timestamp or - date is limited if you use a year longer than 4-digits. You must + date is restricted if you use a year with more than 4 digits. You must use some non-digit character or template after YYYY, - otherwise the year is always interpreted as 4-digits. For example + otherwise the year is always interpreted as 4 digits. For example (with year 20000): to_date('200001131', 'YYYYMMDD') will be - interpreted as a 4-digit year, better is to use a non-digit + interpreted as a 4-digit year; better is to use a non-digit separator after the year, like to_date('20000-1131', 'YYYY-MMDD') or to_date('20000Nov31', 'YYYYMonDD'). @@ -1013,31 +1554,31 @@ S - negative value with minus sign (use locales) + negative value with minus sign (uses locale) L - currency symbol (use locales) + currency symbol (uses locale) D - decimal point (use locales) + decimal point (uses locale) G - group separator (use locales) + group separator (uses locale) MI - minus sign on specified position (if number < 0) + minus sign in specified position (if number < 0) PL - plus sign on specified position (if number > 0) + plus sign in specified position (if number > 0) SG - plus/minus sign on specified position + plus/minus sign in specified position RN @@ -1049,12 +1590,12 @@ V - Shift n digits (see + shift n digits (see notes) EEEE - science numbers. Now not supported. + scientific numbers (not supported yet) @@ -1073,7 +1614,7 @@ but to_char(-12, 'MI9999') produces '- 12'. The Oracle implementation does not allow the use of MI ahead of 9, but rather - requires that 9 preceeds + requires that 9 preceed MI. @@ -1110,8 +1651,8 @@ n is the number of digits following V. to_char does not support the use of - V combined with a decimal point - (e.g. "99.9V99" is not allowed). + V combined with a decimal point. + (E.g., 99.9V99 is not allowed.) @@ -1267,16 +1808,275 @@ - - Geometric Functions + + Date/Time Functions - The geometric types point, box, lseg, line, path, polygon, and - circle have a large set of native support functions. + The date/time functions provide a powerful set of tools + for manipulating various date/time types. + Date/Time Functions + + + + Function + Returns + Description + Example + + + + + abstime(timestamp) + abstime + convert to abstime + abstime(timestamp 'now') + + + age(timestamp) + interval + preserve months and years + age(timestamp '1957-06-13') + + + age(timestamp,timestamp) + interval + preserve months and years + age('now', timestamp '1957-06-13') + + + date_part(text,timestamp) + float8 + portion of date + date_part('dow',timestamp 'now') + + + date_part(text,interval) + float8 + portion of time + date_part('hour',interval '4 hrs 3 mins') + + + date_trunc(text,timestamp) + timestamp + truncate date + date_trunc('month',abstime 'now') + + + interval(reltime) + interval + convert to interval + interval(reltime '4 hours') + + + isfinite(timestamp) + bool + a finite time? + isfinite(timestamp 'now') + + + isfinite(interval) + bool + a finite time? + isfinite(interval '4 hrs') + + + reltime(interval) + reltime + convert to reltime + reltime(interval '4 hrs') + + + timestamp(date) + timestamp + convert to timestamp + timestamp(date 'today') + + + timestamp(date,time) + timestamp + convert to timestamp + timestamp(timestamp '1998-02-24',time '23:07'); + + + to_char(timestamp,text) + text + convert to string + to_char(timestamp '1998-02-24','DD'); + + + +
+
+ + + For the + date_part and date_trunc + functions, arguments can be + `year', `month', + `day', `hour', + `minute', and `second', + as well as the more specialized quantities + `decade', `century', + `millennium', `millisecond', + and `microsecond'. + date_part allows `dow' + to return day of week, 'week' to return the + ISO-defined week of year, and `epoch' to return + seconds since 1970 (for timestamp) + or 'epoch' to return total elapsed seconds + (for interval). + +
+ + + + Geometric Functions and Operators + + + The geometric types point, box, lseg, line, path, polygon, and + circle have a large set of native support functions and operators. + + + + Geometric Operators + + + + Operator + Description + Usage + + + + + + + Translation + '((0,0),(1,1))'::box + '(2.0,0)'::point + + + - + Translation + '((0,0),(1,1))'::box - '(2.0,0)'::point + + + * + Scaling/rotation + '((0,0),(1,1))'::box * '(2.0,0)'::point + + + / + Scaling/rotation + '((0,0),(2,2))'::box / '(2.0,0)'::point + + + # + Intersection + '((1,-1),(-1,1))' # '((1,1),(-1,-1))' + + + # + Number of points in polygon + # '((1,0),(0,1),(-1,0))' + + + ## + Point of closest proximity + '(0,0)'::point ## '((2,0),(0,2))'::lseg + + + && + Overlaps? + '((0,0),(1,1))'::box && '((0,0),(2,2))'::box + + + &< + Overlaps to left? + '((0,0),(1,1))'::box &< '((0,0),(2,2))'::box + + + &> + Overlaps to right? + '((0,0),(3,3))'::box &> '((0,0),(2,2))'::box + + + <-> + Distance between + '((0,0),1)'::circle <-> '((5,0),1)'::circle + + + << + Left of? + '((0,0),1)'::circle << '((5,0),1)'::circle + + + <^ + Is below? + '((0,0),1)'::circle <^ '((0,5),1)'::circle + + + >> + Is right of? + '((5,0),1)'::circle >> '((0,0),1)'::circle + + + >^ + Is above? + '((0,5),1)'::circle >^ '((0,0),1)'::circle + + + ?# + Intersects or overlaps + '((-1,0),(1,0))'::lseg ?# '((-2,-2),(2,2))'::box; + + + ?- + Is horizontal? + '(1,0)'::point ?- '(0,0)'::point + + + ?-| + Is perpendicular? + '((0,0),(0,1))'::lseg ?-| '((0,0),(1,0))'::lseg + + + @-@ + Length or circumference + @-@ '((0,0),(1,0))'::path + + + ?| + Is vertical? + '(0,1)'::point ?| '(0,0)'::point + + + ?|| + Is parallel? + '((-1,0),(1,0))'::lseg ?|| '((-1,2),(1,2))'::lseg + + + @ + Contained or on + '(1,1)'::point @ '((0,0),2)'::circle + + + @@ + Center of + @@ '((0,0),10)'::circle + + + ~= + Same as + '((0,0),(1,1))'::polygon ~= '((1,1),(0,0))'::polygon + + + +
+ + Geometric Functions @@ -1377,11 +2177,10 @@ Not defined by this name. Implements the intersection operator '#' -
-
+ - - + +
Geometric Type Conversion Functions @@ -1485,14 +2284,91 @@ Not defined by this name. Implements the intersection operator '#' -
-
+ + - + + Network Address Type Functions - + + + <type>cidr</> and <type>inet</> Operators + + + + Operator + Description + Usage + + + + + < + Less than + inet '192.168.1.5' < inet '192.168.1.6' + + + <= + Less than or equal + inet '192.168.1.5' <= inet '192.168.1.5' + + + = + Equals + inet '192.168.1.5' = inet '192.168.1.5' + + + >= + Greater or equal + inet '192.168.1.5' >= inet '192.168.1.5' + + + > + Greater + inet '192.168.1.5' > inet '192.168.1.4' + + + <> + Not equal + inet '192.168.1.5' <> inet '192.168.1.4' + + + << + is contained within + inet '192.168.1.5' << inet '192.168.1/24' + + + <<= + is contained within or equals + inet '192.168.1/24' <<= inet '192.168.1/24' + + + >> + contains + inet'192.168.1/24' >> inet '192.168.1.5' + + + >>= + contains or equals + inet '192.168.1/24' >>= inet '192.168.1/24' + + + +
+ + + All of the operators for inet can be applied to + cidr values as well. The operators + <<, <<=, + >>, >>= + test for subnet inclusion: they consider only the network parts + of the two addresses, ignoring any host part, and determine whether + one network part is identical to or a subnet of the other. + + + <type>cidr</> and <type>inet</> Functions @@ -1551,7 +2427,6 @@ Not defined by this name. Implements the intersection operator '#'
-
All of the functions for inet can be applied to @@ -1594,9 +2469,159 @@ Not defined by this name. Implements the intersection operator '#' utilities to create and maintain such an association table. + + The macaddr type also supports the standard relational + operators (>, <=, etc.) for + lexicographical ordering. + +
- + + + Conditional Expressions + + + This section descibes the SQL-compliant conditional expressions + available in Postgres. + + + + + If your needs go beyond the capabilities of these conditional + expressions you might want to consider writing a stored procedure + in a more expressive programming language. + + + + CASE + + +CASE WHEN condition THEN result + WHEN ... + ELSE result +END + + + + The SQL CASE expression is a + generic conditional expression, similar to if/else statements in + other languages. CASE clauses can be used whereever + an expression is valid. condition is an + expression that returns a boolean result. If the result is true + then the value of the CASE expression is + result. If the result is false any + subsequent WHEN clauses are searched in the same + manner. If no WHEN + condition is true then the value of the + case expression is the result in the + ELSE clause. If the ELSE clause is + omitted and no condition matches, the result is NULL. + + + + + An example: + +=> SELECT * FROM test; + + a +--- + 1 + 2 + 3 + + +=> SELECT a, CASE WHEN a=1 THEN 'one' WHEN a=2 THEN 'two' ELSE 'other' END FROM test; + + a | case +---+------- + 1 | one + 2 | two + 3 | other + + + + + + + The data types of all possible result + expressions must match. + + + +CASE expression + WHEN value THEN result + WHEN ... + ELSE result +END + + + + This simple CASE expression is a + specialized variant of the general form above. The + expression is computed and compared to + all the values in the + WHEN clauses until one is found that is equal. If + no match is found, the result in the + ELSE clause (or NULL) is returned. This is similar + to the switch statement in C. + + + + + The example above can be written using the simple + CASE syntax: + +=> SELECT a, CASE a WHEN 1 THEN 'one' WHEN 2 THEN 'two' ELSE 'other' END FROM test; + + a | case +---+------- + 1 | one + 2 | two + 3 | other + + + + + + COALESCE + + +COALESCE(value, ...) + + + + The COALESCE function returns the first of its + arguments that is not NULL. This is often useful to substitute a + default value for NULL values when data is retrieved for display, + for example: + +SELECT COALESCE(description, short_description, '(none)') ... + + + + NULLIF + + +NULLIF(value1, value2) + + + + The NULLIF function returns NULL if and only + if value1 and + value2 are equal. Otherwise it returns + value1. This can be used to perform the + inverse operation of the COALESCE example + given above: + +SELECT NULLIF(value, '(none)') ... + + + + + + Miscellaneous Functions</> <table> @@ -1613,14 +2638,14 @@ Not defined by this name. Implements the intersection operator '#' <entry>user name of current execution context</> </row> <row> - <entry>user</> + <entry>session_user</> <entry>name</> - <entry>equivalent to <function>current_user</></> + <entry>session user name</> </row> <row> - <entry>session_user</> + <entry>user</> <entry>name</> - <entry>session user name</> + <entry>equivalent to <function>current_user</></> </row> </tbody> </tgroup> @@ -1651,135 +2676,135 @@ Not defined by this name. Implements the intersection operator '#' </note> </sect1> - <sect1 id="aggregate-functions"> - <title>Aggregate Functions - - Author - - Written by Isaac Wilcox - on 2000-06-16. - - + + Aggregate Functions + + Author - Aggregate functions allow the generation of simple - statistics about the values of given expressions over the selected set - of rows. - - See also ; - refer to - the PostgreSQL Tutorial for additional - introductory information. + Written by Isaac Wilcox isaac@azartmedia.com on 2000-06-16 + - - - Aggregate Functions - - - - - Function - Returns - Description - Example - Notes - - - - - - COUNT(*) - int4 - Counts the selected rows. - COUNT(*) - - - - - COUNT(expression) - int4 - Counts the selected rows for which the value of - expression is not - NULL. - COUNT(age) - - - - - SUM(expression) - Depends on the data type being summed. - Finds the total obtained by adding the values of expression across all selected rows. - SUM(hours) - Summation is supported on the following data types: int8, int4, - int2, float4, float8, money, interval, numeric. The result is numeric - for any integer type, float8 for either float4 or float8 input, - otherwise the same as the input data type. - - - - MAX(expression) - Same as the data type of the input expression. - The maximum value of expression across all selected rows. - MAX(age) - Finding the maximum value is supported on the following data types: int8, int4, int2, float4, float8, date, time, timetz, money, timestamp, interval, text, numeric. - - - - MIN(expression) - Same as the data type of the input expression. - The minimum value of expression across all selected rows. - MIN(age) - Finding the minimum value is supported on the following data types: int8, int4, int2, float4, float8, date, time, timetz, money, timestamp, interval, text, numeric. - + + Aggregate functions compute a single result + value from a set of input values. The special syntax + considerations for aggregate functions are explained in . Consult the PostgreSQL + Tutorial for additional introductory information. + - - AVG(expression) - Depends on the data type being averaged. - The average (mean) of the given values across all selected rows. - AVG(age+1) - Finding the mean value is supported on the following data - types: int8, int4, int2, float4, float8, interval, numeric. The - result is numeric for any integer type, float8 for either float4 or - float8 input, otherwise the same as the input data type. - +
+ Aggregate Functions - - VARIANCE(expression) - Depends on the input data type. - The sample variance of the given values. - VARIANCE(reading) - Finding the variance is supported on the following data - types: int8, int4, int2, float4, float8, numeric. The result is - float8 for float4 or float8 input, otherwise numeric. - + + + + Function + Description + Notes + + + + + + AVG(expression) + the average (arithmetic mean) of all input values + + Finding the average value is available on the following data + types: smallint, integer, + bigint, real, double + precision, numeric, interval. + The result is of type numeric for any integer type + input, double precision for floating point input, + otherwise the same as the input data type. + + + + + COUNT(*) + number of input values + The return value is of type integer. + + + + COUNT(expression) + + Counts the input values for which the value of expression is not NULL. + + + + + + MAX(expression) + the maximum value of expression across all input values + + Available for all numeric, string, and date/time types. The + result has the same type as the input expression. + + + + + MIN(expression) + the minimum value of expression across all input values + + Available for all numeric, string, and date/time types. The + result has the same type as the input expression. + + + + + STDDEV(expression) + the sample standard deviation of the input values + + Finding the standard deviation is available on the following + data types: smallint, integer, + bigint, real, double + precision, numeric. The result is of type + double precision for floating point input, + otherwise numeric. + + + + + SUM(expression) + sum of expression across all input values + + Summation is available on the following data types: + smallint, integer, + bigint, real, double + precision, numeric, interval. + The result is of type numeric for any integer type + input, double precision for floating point input, + otherwise the same as the input data type. + + + + + VARIANCE(expression) + the sample variance of the input values + + The variance is the square of the standard deviation. The + supported data types are the same. + + + + + +
- - STDDEV(expression) - Depends on the input data type. - The sample standard deviation of the given values. - STDDEV(reading) - Finding the standard deviation is supported on the following - data types: int8, int4, int2, float4, float8, numeric. The result is - float8 for float4 or float8 input, otherwise numeric. - + + It should be noted that except for COUNT, + these functions return NULL when no rows are selected. In + particular, SUM of no rows returns NULL, not + zero as one might expect. + - - - -
+
- - It should be noted that except for COUNT, these functions return NULL - when no rows are selected. In particular, SUM of no rows returns NULL, - not zero as one might expect. - -
-
+ - - - Operators - - - - Describes the built-in operators available in - Postgres. - - - - - Postgres provides a large number of - built-in operators on system types. - These operators are declared in the system catalog - pg_operator. Every entry in pg_operator includes - the name of the procedure that implements the operator and the - class OIDs of the input and output types. - - - - To view all variations of the "||" string concatenation operator, - try - - SELECT oprleft, oprright, oprresult, oprcode - FROM pg_operator WHERE oprname = '||'; - -oprleft|oprright|oprresult|oprcode --------+--------+---------+------- - 25| 25| 25|textcat - 1042| 1042| 1042|textcat - 1043| 1043| 1043|textcat -(3 rows) - - - - - Users may invoke operators using the operator name, as in: - - -select * from emp where salary < 40000; - - - Alternatively, users may call the functions that implement the - operators directly. In this case, the query above would be expressed - as: - -select * from emp where int4lt(salary, 40000); - - - - - psql - has a command (\dd) to show these operators. - - - - Lexical Precedence - - - Operators have a precedence which is currently hardcoded into the parser. - Most operators have the same precedence and are left-associative. This may lead - to non-intuitive behavior; for example the boolean operators "<" and ">" - have a different precedence than the boolean operators "<=" and ">=". - - - -Operator Ordering (decreasing precedence) - - - - - -Element -Precedence -Description - - - - - - -:: - - -left - - -Postgres typecasting - - - - -[ ] - - -left - - -array delimiters - - - - -. - - -left - - -table/column delimiter - - - - -- - - -right - - -unary minus - - - - -| - - -left - - -start of interval - - - - -^ - - -left - - -power, exclusive or - - - - -* / % - - -left - - -multiplication, division, modulo - - - - -+ - - - -left - - -addition, subtraction - - - - -IS - - - - -test for TRUE, FALSE, NULL - - - - -ISNULL - - - - -test for NULL - - - - -NOTNULL - - - - -test for NOT NULL - - - - -(all other operators) - - -left - - -native and user-defined - - - - -IN - - - - -set membership - - - - -BETWEEN - - - - -containment - - - - -OVERLAPS - - - - -time interval overlap - - - - -LIKE ILIKE - - - - -string pattern matching - - - - -< > - - - - -inequality - - - - -= - - -right - - -equality - - - - -NOT - - -right - - -logical negation - - - - -AND - - -left - - -logical intersection - - - - -OR - - -left - - -logical union - - - - -
-
-
- - - General Operators - - - The operators listed here are defined for a number of native data types, - ranging from numeric types to data/time types. - - - - - <ProductName>Postgres</ProductName> Operators - Operators - - - - Operator - Description - Usage - - - - - < - Less than? - 1 < 2 - - - <= - Less than or equal to? - 1 <= 2 - - - <> - Not equal? - 1 <> 2 - - - = - Equal? - 1 = 1 - - - > - Greater than? - 2 > 1 - - - >= - Greater than or equal to? - 2 >= 1 - - - || - Concatenate strings - 'Postgre' || 'SQL' - - - !!= - NOT IN - 3 !!= i - - - ~~ - LIKE - 'scrappy,marc,hermit' ~~ '%scrappy%' - - - !~~ - NOT LIKE - 'bruce' !~~ '%al%' - - - ~~* - ILIKE - 'scrappy,marc,hermit' ~~* '%Scrappy%' - - - !~~* - NOT ILIKE - 'Bruce' !~~* '%al%' - - - ~ - Match (regex), case sensitive - 'thomas' ~ '.*thomas.*' - - - ~* - Match (regex), case insensitive - 'thomas' ~* '.*Thomas.*' - - - !~ - Does not match (regex), case sensitive - 'thomas' !~ '.*Thomas.*' - - - !~* - Does not match (regex), case insensitive - 'thomas' !~* '.*vadim.*' - - - -
-
-
- - - Numerical Operators - - - - <ProductName>Postgres</ProductName> Numerical Operators - Operators - - - - Operator - Description - Usage - - - - - ! - Factorial - 3 ! - - - !! - Factorial (left operator) - !! 3 - - - % - Modulo - 5 % 4 - - - % - Truncate - % 4.5 - - - * - Multiplication - 2 * 3 - - - + - Addition - 2 + 3 - - - - - Subtraction - 2 - 3 - - - / - Division - 4 / 2 - - - @ - Absolute value - @ -5.0 - - - ^ - Exponentiation - 2.0 ^ 3.0 - - - |/ - Square root - |/ 25.0 - - - ||/ - Cube root - ||/ 27.0 - - - & - Binary AND - 91 & 15 - - - | - Binary OR - 32 | 3 - - - # - Binary XOR - 15 # 4 - - - ~ - Binary NOT - ~1 - - - << - Binary shift left - 1 << 4 - - - >> - Binary shift right - 8 >> 2 - - - -
-
-
- - - Geometric Operators - - - - <ProductName>Postgres</ProductName> Geometric Operators - Operators - - - - Operator - Description - Usage - - - - - + - Translation - '((0,0),(1,1))'::box + '(2.0,0)'::point - - - - - Translation - '((0,0),(1,1))'::box - '(2.0,0)'::point - - - * - Scaling/rotation - '((0,0),(1,1))'::box * '(2.0,0)'::point - - - / - Scaling/rotation - '((0,0),(2,2))'::box / '(2.0,0)'::point - - - # - Intersection - '((1,-1),(-1,1))' # '((1,1),(-1,-1))' - - - # - Number of points in polygon - # '((1,0),(0,1),(-1,0))' - - - ## - Point of closest proximity - '(0,0)'::point ## '((2,0),(0,2))'::lseg - - - && - Overlaps? - '((0,0),(1,1))'::box && '((0,0),(2,2))'::box - - - &< - Overlaps to left? - '((0,0),(1,1))'::box &< '((0,0),(2,2))'::box - - - &> - Overlaps to right? - '((0,0),(3,3))'::box &> '((0,0),(2,2))'::box - - - <-> - Distance between - '((0,0),1)'::circle <-> '((5,0),1)'::circle - - - << - Left of? - '((0,0),1)'::circle << '((5,0),1)'::circle - - - <^ - Is below? - '((0,0),1)'::circle <^ '((0,5),1)'::circle - - - >> - Is right of? - '((5,0),1)'::circle >> '((0,0),1)'::circle - - - >^ - Is above? - '((0,5),1)'::circle >^ '((0,0),1)'::circle - - - ?# - Intersects or overlaps - '((-1,0),(1,0))'::lseg ?# '((-2,-2),(2,2))'::box; - - - ?- - Is horizontal? - '(1,0)'::point ?- '(0,0)'::point - - - ?-| - Is perpendicular? - '((0,0),(0,1))'::lseg ?-| '((0,0),(1,0))'::lseg - - - @-@ - Length or circumference - @-@ '((0,0),(1,0))'::path - - - ?| - Is vertical? - '(0,1)'::point ?| '(0,0)'::point - - - ?|| - Is parallel? - '((-1,0),(1,0))'::lseg ?|| '((-1,2),(1,2))'::lseg - - - @ - Contained or on - '(1,1)'::point @ '((0,0),2)'::circle - - - @@ - Center of - @@ '((0,0),10)'::circle - - - ~= - Same as - '((0,0),(1,1))'::polygon ~= '((1,1),(0,0))'::polygon - - - -
-
-
- - - Time Interval Operators - - - The time interval data type tinterval is a legacy from the original - date/time types and is not as well supported as the more modern types. There - are several operators for this type. - - - <ProductName>Postgres</ProductName> Time Interval Operators - Operators - - - - Operator - Description - Usage - - - - - #< - Interval less than? - - - - #<= - Interval less than or equal to? - - - - #<> - Interval not equal? - - - - #= - Interval equal? - - - - #> - Interval greater than? - - - - #>= - Interval greater than or equal to? - - - - <#> - Convert to time interval - - - - << - Interval less than? - - - - | - Start of interval - - - - ~= - Same as - - - - <?> - Time inside interval? - - - - -
-
-
- - - - Network Address Type Operators - - - <type>cidr</> and <type>inet</> Operators - - - <type>cidr</> and <type>inet</> Operators - - - - Operator - Description - Usage - - - - - < - Less than - '192.168.1.5'::inet < '192.168.1.6'::inet - - - <= - Less than or equal - '192.168.1.5'::inet <= '192.168.1.5'::inet - - - = - Equals - '192.168.1.5'::inet = '192.168.1.5'::inet - - - >= - Greater or equal - '192.168.1.5'::inet >= '192.168.1.5'::inet - - - > - Greater - '192.168.1.5'::inet > '192.168.1.4'::inet - - - <> - Not equal - '192.168.1.5'::inet <> '192.168.1.4'::inet - - - << - is contained within - '192.168.1.5'::inet << '192.168.1/24'::inet - - - <<= - is contained within or equals - '192.168.1/24'::inet <<= '192.168.1/24'::inet - - - >> - contains - '192.168.1/24'::inet >> '192.168.1.5'::inet - - - >>= - contains or equals - '192.168.1/24'::inet >>= '192.168.1/24'::inet - - - -
- - - All of the operators for inet can be applied to - cidr values as well. The operators - << <<= - >> >>= - test for subnet inclusion: they consider only the network parts - of the two addresses, ignoring any host part, and determine whether - one network part is identical to or a subnet of the other. - -
- - - <type>macaddr</> Operators</> - - <para> - The <type>macaddr</> type supports the standard relational - operators (<literal>></>, <literal><=</>, etc.) for - lexicographical ordering. - </para> - </sect2> - - </sect1> - - </Chapter> - -<!-- Keep this comment at the end of the file -Local variables: -mode:sgml -sgml-omittag:nil -sgml-shorttag:t -sgml-minimize-attributes:nil -sgml-always-quote-attributes:t -sgml-indent-step:1 -sgml-indent-data:t -sgml-parent-document:nil -sgml-default-dtd-file:"./reference.ced" -sgml-exposed-tags:nil -sgml-local-catalogs:("/usr/lib/sgml/catalog") -sgml-local-ecat-files:nil -End: ---> diff --git a/doc/src/sgml/syntax.sgml b/doc/src/sgml/syntax.sgml index 2749549a19..0537f531ef 100644 --- a/doc/src/sgml/syntax.sgml +++ b/doc/src/sgml/syntax.sgml @@ -1,5 +1,5 @@ <!-- -$Header: /cvsroot/pgsql/doc/src/sgml/syntax.sgml,v 1.25 2000/09/29 20:21:34 petere Exp $ +$Header: /cvsroot/pgsql/doc/src/sgml/syntax.sgml,v 1.26 2000/12/14 22:30:56 petere Exp $ --> <chapter id="syntax"> @@ -656,7 +656,7 @@ CAST ( '<replaceable>string</replaceable>' AS <replaceable>type</replaceable> ) <para> Any built-in system, or user-defined operator may be used in SQL. For the list of built-in and system operators consult - <xref linkend="operators" endterm="operators-title">. + <xref linkend="functions">. For a list of user-defined operators consult your system administrator or run a query on the <literal>pg_operator</literal> class. Parentheses may be used for arbitrary grouping of operators in expressions. @@ -669,10 +669,7 @@ CAST ( '<replaceable>string</replaceable>' AS <replaceable>type</replaceable> ) <para> <acronym>SQL92</acronym> allows <firstterm>expressions</firstterm> to transform data in tables. Expressions may contain operators - (see <xref linkend="operators" endterm="operators-title"> - for more details) and functions - (<xref linkend="functions" endterm="functions-title"> has - more information). + and functions. </para> <para> @@ -749,8 +746,8 @@ sqrt(emp.salary) </para> </sect2> - <sect2> - <title id="aggregates-syntax">Aggregate Expressions + + Aggregate Expressions An aggregate expression represents the application @@ -863,6 +860,177 @@ sqrt(emp.salary) before the classname. + + + + Lexical Precedence + + + The precedence and associativity of the operators is hard-wired + into the parser. Most operators have the same precedence and are + left-associative. This may lead to non-intuitive behavior; for + example the boolean operators "<" and ">" have a different + precedence than the boolean operators "<=" and ">=". Also, + you will sometimes need to add parenthesis when using combinations + of binary and unary operators. For instance + +SELECT 5 & ~ 6; + + will be parsed as + +SELECT (5 &) ~ 6; + + because the parser has no idea that & is + defined as a binary operator. This is the price one pays for + extensibility. + + + + Operator Ordering (decreasing precedence) + + + + + OperatorElement + Associativity + Description + + + + + + :: + left + Postgres-style typecast + + + + [ ] + left + array element selection + + + + . + left + table/column name separator + + + + - + right + unary minus + + + + ^ + left + exponentiation + + + + * / % + left + multiplication, division, modulo + + + + + - + left + addition, subtraction + + + + IS + + test for TRUE, FALSE, NULL + + + + ISNULL + + test for NULL + + + + NOTNULL + + test for NOT NULL + + + + (any other) + left + all other native and user-defined operators + + + + IN + + set membership + + + + BETWEEN + + containment + + + + OVERLAPS + + time interval overlap + + + + LIKE ILIKE + + string pattern matching + + + + < > + + less than, greater than + + + + = + right + equality, assignment + + + + NOT + right + logical negation + + + + AND + left + logical conjunction + + + + OR + left + logical disjunction + + + +
+ + + Note that the operator precedence rules also apply to user-defined + operators that look like the built-in operators + with special treatment. For example, if you define a + + operator for some custom data type it will have + the same precedence as the built-in + operator, no + matter what yours does. + +
+
diff --git a/doc/src/sgml/user.sgml b/doc/src/sgml/user.sgml index e4aa8267a4..64922acc39 100644 --- a/doc/src/sgml/user.sgml +++ b/doc/src/sgml/user.sgml @@ -1,5 +1,5 @@ @@ -45,11 +45,10 @@ $Header: /cvsroot/pgsql/doc/src/sgml/Attic/user.sgml,v 1.20 2000/11/24 17:44:22 &intro; &syntax; &datatype; - &oper; &func; &typeconv; - &indices; &array; + &indices; &inherit; &plsql; &pltcl;