2010-09-20 22:08:53 +02:00
<!-- doc/src/sgml/syntax.sgml -->
2000-03-31 05:27:42 +02:00
2001-01-06 12:58:56 +01:00
<chapter id="sql-syntax">
<title>SQL Syntax</title>
1999-05-12 09:32:47 +02:00
2001-05-13 00:51:36 +02:00
<indexterm zone="sql-syntax">
<primary>syntax</primary>
<secondary>SQL</secondary>
</indexterm>
2002-08-05 21:43:31 +02:00
<para>
This chapter describes the syntax of SQL. It forms the foundation
for understanding the following chapters which will go into detail
2009-04-27 18:27:36 +02:00
about how SQL commands are applied to define and modify data.
2002-08-05 21:43:31 +02:00
</para>
<para>
We also advise users who are already familiar with SQL to read this
2009-04-27 18:27:36 +02:00
chapter carefully because it contains several rules and concepts that
2002-08-05 21:43:31 +02:00
are implemented inconsistently among SQL databases or that are
specific to <productname>PostgreSQL</productname>.
</para>
1999-05-12 09:32:47 +02:00
2001-01-06 12:58:56 +01:00
<sect1 id="sql-syntax-lexical">
<title>Lexical Structure</title>
2003-08-31 19:32:24 +02:00
<indexterm>
<primary>token</primary>
</indexterm>
1999-07-22 17:11:05 +02:00
<para>
2001-01-06 12:58:56 +01:00
SQL input consists of a sequence of
<firstterm>commands</firstterm>. A command is composed of a
2001-01-21 23:02:01 +01:00
sequence of <firstterm>tokens</firstterm>, terminated by a
semicolon (<quote>;</quote>). The end of the input stream also
terminates a command. Which tokens are valid depends on the syntax
of the particular command.
1999-07-22 17:11:05 +02:00
</para>
2001-01-06 12:58:56 +01:00
<para>
A token can be a <firstterm>key word</firstterm>, an
<firstterm>identifier</firstterm>, a <firstterm>quoted
identifier</firstterm>, a <firstterm>literal</firstterm> (or
constant), or a special character symbol. Tokens are normally
separated by whitespace (space, tab, newline), but need not be if
there is no ambiguity (which is generally only the case if a
special character is adjacent to some other token type).
</para>
1999-05-12 09:32:47 +02:00
<para>
2001-01-21 23:02:01 +01:00
For example, the following is (syntactically) valid SQL input:
2001-01-06 12:58:56 +01:00
<programlisting>
2010-08-12 04:03:58 +02:00
SELECT * FROM MY_TABLE;
UPDATE MY_TABLE SET A = 5;
INSERT INTO MY_TABLE VALUES (3, 'hi there');
2001-01-06 12:58:56 +01:00
</programlisting>
This is a sequence of three commands, one per line (although this
is not required; more than one command can be on a line, and
2001-02-10 08:08:44 +01:00
commands can usefully be split across lines).
1999-05-12 09:32:47 +02:00
</para>
2001-01-06 12:58:56 +01:00
2010-08-13 03:12:38 +02:00
<para>
Additionally, <firstterm>comments</firstterm> can occur in SQL
input. They are not tokens, they are effectively equivalent to
whitespace.
</para>
2001-01-06 12:58:56 +01:00
<para>
The SQL syntax is not very consistent regarding what tokens
identify commands and which are operands or parameters. The first
few tokens are generally the command name, so in the above example
we would usually speak of a <quote>SELECT</quote>, an
<quote>UPDATE</quote>, and an <quote>INSERT</quote> command. But
for instance the <command>UPDATE</command> command always requires
a <token>SET</token> token to appear in a certain position, and
this particular variation of <command>INSERT</command> also
requires a <token>VALUES</token> in order to be complete. The
2003-03-25 17:15:44 +01:00
precise syntax rules for each command are described in <xref linkend="reference">.
2001-01-06 12:58:56 +01:00
</para>
<sect2 id="sql-syntax-identifiers">
<title>Identifiers and Key Words</title>
1999-05-12 09:32:47 +02:00
2001-05-13 00:51:36 +02:00
<indexterm zone="sql-syntax-identifiers">
2003-08-31 19:32:24 +02:00
<primary>identifier</primary>
<secondary>syntax of</secondary>
2001-05-13 00:51:36 +02:00
</indexterm>
<indexterm zone="sql-syntax-identifiers">
2003-08-31 19:32:24 +02:00
<primary>name</primary>
<secondary>syntax of</secondary>
</indexterm>
<indexterm zone="sql-syntax-identifiers">
<primary>key word</primary>
<secondary>syntax of</secondary>
2001-05-13 00:51:36 +02:00
</indexterm>
1999-05-12 09:32:47 +02:00
<para>
2001-01-06 12:58:56 +01:00
Tokens such as <token>SELECT</token>, <token>UPDATE</token>, or
<token>VALUES</token> in the example above are examples of
<firstterm>key words</firstterm>, that is, words that have a fixed
meaning in the SQL language. The tokens <token>MY_TABLE</token>
and <token>A</token> are examples of
<firstterm>identifiers</firstterm>. They identify names of
tables, columns, or other database objects, depending on the
command they are used in. Therefore they are sometimes simply
called <quote>names</quote>. Key words and identifiers have the
same lexical structure, meaning that one cannot know whether a
token is an identifier or a key word without knowing the language.
A complete list of key words can be found in <xref
linkend="sql-keywords-appendix">.
1999-05-12 09:32:47 +02:00
</para>
<para>
2001-01-06 12:58:56 +01:00
SQL identifiers and key words must begin with a letter
2002-01-07 03:29:15 +01:00
(<literal>a</literal>-<literal>z</literal>, but also letters with
diacritical marks and non-Latin letters) or an underscore
2001-01-06 12:58:56 +01:00
(<literal>_</literal>). Subsequent characters in an identifier or
2003-06-20 01:22:40 +02:00
key word can be letters, underscores, digits
(<literal>0</literal>-<literal>9</literal>), or dollar signs
(<literal>$</>). Note that dollar signs are not allowed in identifiers
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
according to the letter of the SQL standard, so their use might render
2003-06-20 01:22:40 +02:00
applications less portable.
The SQL standard will not define a key word that contains
digits or starts or ends with an underscore, so identifiers of this
form are safe against possible conflict with future extensions of the
standard.
1999-05-12 09:32:47 +02:00
</para>
1999-07-22 17:11:05 +02:00
<para>
2003-08-31 19:32:24 +02:00
<indexterm><primary>identifier</primary><secondary>length</secondary></indexterm>
2001-01-06 12:58:56 +01:00
The system uses no more than <symbol>NAMEDATALEN</symbol>-1
Support arrays of composite types, including the rowtypes of regular tables
and views (but not system catalogs, nor sequences or toast tables). Get rid
of the hardwired convention that a type's array type is named exactly "_type",
instead using a new column pg_type.typarray to provide the linkage. (It still
will be named "_type", though, except in odd corner cases such as
maximum-length type names.)
Along the way, make tracking of owner and schema dependencies for types more
uniform: a type directly created by the user has these dependencies, while a
table rowtype or auto-generated array type does not have them, but depends on
its parent object instead.
David Fetter, Andrew Dunstan, Tom Lane
2007-05-11 19:57:14 +02:00
bytes of an identifier; longer names can be written in
2001-01-06 12:58:56 +01:00
commands, but they will be truncated. By default,
2002-11-15 04:11:18 +01:00
<symbol>NAMEDATALEN</symbol> is 64 so the maximum identifier
Support arrays of composite types, including the rowtypes of regular tables
and views (but not system catalogs, nor sequences or toast tables). Get rid
of the hardwired convention that a type's array type is named exactly "_type",
instead using a new column pg_type.typarray to provide the linkage. (It still
will be named "_type", though, except in odd corner cases such as
maximum-length type names.)
Along the way, make tracking of owner and schema dependencies for types more
uniform: a type directly created by the user has these dependencies, while a
table rowtype or auto-generated array type does not have them, but depends on
its parent object instead.
David Fetter, Andrew Dunstan, Tom Lane
2007-05-11 19:57:14 +02:00
length is 63 bytes. If this limit is problematic, it can be raised by
2003-02-19 04:13:25 +01:00
changing the <symbol>NAMEDATALEN</symbol> constant in
2007-02-06 10:16:08 +01:00
<filename>src/include/pg_config_manual.h</filename>.
2000-07-14 17:26:21 +02:00
</para>
1999-07-22 17:11:05 +02:00
2000-07-14 17:26:21 +02:00
<para>
2001-05-13 00:51:36 +02:00
<indexterm>
<primary>case sensitivity</primary>
2003-08-31 19:32:24 +02:00
<secondary>of SQL commands</secondary>
2001-05-13 00:51:36 +02:00
</indexterm>
2010-02-04 01:19:28 +01:00
Key words and unquoted identifiers are case insensitive. Therefore:
2001-01-06 12:58:56 +01:00
<programlisting>
2010-08-12 04:03:58 +02:00
UPDATE MY_TABLE SET A = 5;
2001-01-06 12:58:56 +01:00
</programlisting>
2007-02-01 01:28:19 +01:00
can equivalently be written as:
2001-01-06 12:58:56 +01:00
<programlisting>
2010-08-12 04:03:58 +02:00
uPDaTE my_TabLE SeT a = 5;
2001-01-06 12:58:56 +01:00
</programlisting>
2001-02-10 08:08:44 +01:00
A convention often used is to write key words in upper
2007-02-01 01:28:19 +01:00
case and names in lower case, e.g.:
2001-01-06 12:58:56 +01:00
<programlisting>
UPDATE my_table SET a = 5;
</programlisting>
1999-07-22 17:11:05 +02:00
</para>
<para>
2001-05-13 00:51:36 +02:00
<indexterm>
2003-08-31 19:32:24 +02:00
<primary>quotation marks</primary>
2001-05-13 00:51:36 +02:00
<secondary>and identifiers</secondary>
</indexterm>
2001-01-06 12:58:56 +01:00
There is a second kind of identifier: the <firstterm>delimited
identifier</firstterm> or <firstterm>quoted
identifier</firstterm>. It is formed by enclosing an arbitrary
sequence of characters in double-quotes
(<literal>"</literal>). <!-- " font-lock mania --> A delimited
identifier is always an identifier, never a key word. So
<literal>"select"</literal> could be used to refer to a column or
table named <quote>select</quote>, whereas an unquoted
2001-02-10 08:08:44 +01:00
<literal>select</literal> would be taken as a key word and
2001-01-06 12:58:56 +01:00
would therefore provoke a parse error when used where a table or
column name is expected. The example can be written with quoted
2001-02-10 08:08:44 +01:00
identifiers like this:
2001-01-06 12:58:56 +01:00
<programlisting>
UPDATE "my_table" SET "a" = 5;
</programlisting>
1999-09-01 04:37:40 +02:00
</para>
<para>
2006-10-22 05:03:41 +02:00
Quoted identifiers can contain any character, except the character
with code zero. (To include a double quote, write two double quotes.)
2002-11-11 21:14:04 +01:00
This allows constructing table or column names that would
otherwise not be possible, such as ones containing spaces or
2001-01-06 12:58:56 +01:00
ampersands. The length limitation still applies.
1999-07-22 17:11:05 +02:00
</para>
2000-03-31 01:42:34 +02:00
2008-10-29 09:04:54 +01:00
<para>
<indexterm><primary>Unicode escape</primary><secondary>in
identifiers</secondary></indexterm> A variant of quoted
identifiers allows including escaped Unicode characters identified
by their code points. This variant starts
2009-02-04 22:30:41 +01:00
with <literal>U&</literal> (upper or lower case U followed by
2008-10-29 09:04:54 +01:00
ampersand) immediately before the opening double quote, without
2009-02-04 22:30:41 +01:00
any spaces in between, for example <literal>U&"foo"</literal>.
2008-10-29 09:04:54 +01:00
(Note that this creates an ambiguity with the
2009-02-04 22:30:41 +01:00
operator <literal>&</literal>. Use spaces around the operator to
2008-10-29 09:04:54 +01:00
avoid this problem.) Inside the quotes, Unicode characters can be
specified in escaped form by writing a backslash followed by the
four-digit hexadecimal code point number or alternatively a
backslash followed by a plus sign followed by a six-digit
hexadecimal code point number. For example, the
identifier <literal>"data"</literal> could be written as
<programlisting>
2009-02-04 22:30:41 +01:00
U&"d\0061t\+000061"
2008-10-29 09:04:54 +01:00
</programlisting>
The following less trivial example writes the Russian
word <quote>slon</quote> (elephant) in Cyrillic letters:
<programlisting>
2009-02-04 22:30:41 +01:00
U&"\0441\043B\043E\043D"
2008-10-29 09:04:54 +01:00
</programlisting>
</para>
<para>
If a different escape character than backslash is desired, it can
be specified using
the <literal>UESCAPE</literal><indexterm><primary>UESCAPE</primary></indexterm>
clause after the string, for example:
<programlisting>
2009-02-04 22:30:41 +01:00
U&"d!0061t!+000061" UESCAPE '!'
2008-10-29 09:04:54 +01:00
</programlisting>
The escape character can be any single character other than a
hexadecimal digit, the plus sign, a single quote, a double quote,
or a whitespace character. Note that the escape character is
written in single quotes, not double quotes.
</para>
<para>
To include the escape character in the identifier literally, write
it twice.
</para>
<para>
The Unicode escape syntax works only when the server encoding is
2010-09-07 20:54:09 +02:00
<literal>UTF8</>. When other server encodings are used, only code
points in the ASCII range (up to <literal>\007F</literal>) can be
specified. Both the 4-digit and the 6-digit form can be used to
specify UTF-16 surrogate pairs to compose characters with code
points larger than U+FFFF, although the availability of the
2011-02-20 01:00:19 +01:00
6-digit form technically makes this unnecessary. (Surrogate
pairs are not stored directly, but combined into a single
code point that is then encoded in UTF-8.)
2008-10-29 09:04:54 +01:00
</para>
2000-03-31 01:42:34 +02:00
<para>
2001-01-06 12:58:56 +01:00
Quoting an identifier also makes it case-sensitive, whereas
unquoted names are always folded to lower case. For example, the
2003-03-13 02:30:29 +01:00
identifiers <literal>FOO</literal>, <literal>foo</literal>, and
2001-01-06 12:58:56 +01:00
<literal>"foo"</literal> are considered the same by
2003-11-04 10:55:39 +01:00
<productname>PostgreSQL</productname>, but
<literal>"Foo"</literal> and <literal>"FOO"</literal> are
different from these three and each other. (The folding of
unquoted names to lower case in <productname>PostgreSQL</> is
incompatible with the SQL standard, which says that unquoted names
should be folded to upper case. Thus, <literal>foo</literal>
should be equivalent to <literal>"FOO"</literal> not
<literal>"foo"</literal> according to the standard. If you want
to write portable applications you are advised to always quote a
2003-11-06 23:21:47 +01:00
particular name or never quote it.)
2000-03-31 01:42:34 +02:00
</para>
2001-01-06 12:58:56 +01:00
</sect2>
1999-07-22 17:11:05 +02:00
2001-01-06 12:58:56 +01:00
<sect2 id="sql-syntax-constants">
1999-07-22 17:11:05 +02:00
<title>Constants</title>
2001-05-13 00:51:36 +02:00
<indexterm zone="sql-syntax-constants">
2003-08-31 19:32:24 +02:00
<primary>constant</primary>
2001-05-13 00:51:36 +02:00
</indexterm>
1999-07-22 17:11:05 +02:00
<para>
2002-10-20 07:05:46 +02:00
There are three kinds of <firstterm>implicitly-typed
2001-11-21 07:09:45 +01:00
constants</firstterm> in <productname>PostgreSQL</productname>:
2002-10-20 07:05:46 +02:00
strings, bit strings, and numbers.
2001-01-06 12:58:56 +01:00
Constants can also be specified with explicit types, which can
enable more accurate representation and more efficient handling by
2004-09-21 00:48:29 +02:00
the system. These alternatives are discussed in the following
subsections.
1999-07-22 17:11:05 +02:00
</para>
2001-01-21 23:02:01 +01:00
<sect3 id="sql-syntax-strings">
1999-07-22 17:11:05 +02:00
<title>String Constants</title>
2001-05-13 00:51:36 +02:00
<indexterm zone="sql-syntax-strings">
2003-08-31 19:32:24 +02:00
<primary>character string</primary>
<secondary>constant</secondary>
2001-05-13 00:51:36 +02:00
</indexterm>
1999-07-22 17:11:05 +02:00
<para>
2001-05-13 00:51:36 +02:00
<indexterm>
2003-08-31 19:32:24 +02:00
<primary>quotation marks</primary>
2001-05-13 00:51:36 +02:00
<secondary>escaping</secondary>
</indexterm>
2004-09-21 00:48:29 +02:00
A string constant in SQL is an arbitrary sequence of characters
bounded by single quotes (<literal>'</literal>), for example
2006-10-21 19:12:07 +02:00
<literal>'This is a string'</literal>. To include
a single-quote character within a string constant,
2009-04-27 18:27:36 +02:00
write two adjacent single quotes, e.g.,
2004-09-21 00:48:29 +02:00
<literal>'Dianne''s horse'</literal>.
2006-10-21 19:12:07 +02:00
Note that this is <emphasis>not</> the same as a double-quote
2008-10-29 09:04:54 +01:00
character (<literal>"</>). <!-- font-lock sanity: " -->
2001-01-06 12:58:56 +01:00
</para>
1999-07-22 17:11:05 +02:00
2001-01-06 12:58:56 +01:00
<para>
Two string constants that are only separated by whitespace
<emphasis>with at least one newline</emphasis> are concatenated
2006-10-22 05:03:41 +02:00
and effectively treated as if the string had been written as one
2001-01-06 12:58:56 +01:00
constant. For example:
<programlisting>
SELECT 'foo'
'bar';
</programlisting>
2007-02-01 01:28:19 +01:00
is equivalent to:
2001-01-06 12:58:56 +01:00
<programlisting>
SELECT 'foobar';
</programlisting>
2007-02-01 01:28:19 +01:00
but:
2001-01-06 12:58:56 +01:00
<programlisting>
SELECT 'foo' 'bar';
</programlisting>
2002-10-20 07:05:46 +02:00
is not valid syntax. (This slightly bizarre behavior is specified
2002-11-11 21:14:04 +01:00
by <acronym>SQL</acronym>; <productname>PostgreSQL</productname> is
2002-10-20 07:05:46 +02:00
following the standard.)
2001-01-06 12:58:56 +01:00
</para>
2008-10-29 09:04:54 +01:00
</sect3>
2006-10-21 19:12:07 +02:00
2008-10-29 09:04:54 +01:00
<sect3 id="sql-syntax-strings-escape">
2011-02-01 23:00:26 +01:00
<title>String Constants with C-style Escapes</title>
2008-10-29 09:04:54 +01:00
<indexterm zone="sql-syntax-strings-escape">
2006-10-21 19:12:07 +02:00
<primary>escape string syntax</primary>
</indexterm>
2008-10-29 09:04:54 +01:00
<indexterm zone="sql-syntax-strings-escape">
2006-10-21 19:12:07 +02:00
<primary>backslash escapes</primary>
</indexterm>
2008-10-29 09:04:54 +01:00
<para>
2006-10-21 19:12:07 +02:00
<productname>PostgreSQL</productname> also accepts <quote>escape</>
string constants, which are an extension to the SQL standard.
An escape string constant is specified by writing the letter
<literal>E</literal> (upper or lower case) just before the opening single
2009-04-27 18:27:36 +02:00
quote, e.g., <literal>E'foo'</>. (When continuing an escape string
2006-10-21 19:12:07 +02:00
constant across lines, write <literal>E</> only before the first opening
quote.)
Within an escape string, a backslash character (<literal>\</>) begins a
C-like <firstterm>backslash escape</> sequence, in which the combination
2008-06-27 00:24:42 +02:00
of backslash and following character(s) represent a special byte
2008-10-29 09:04:54 +01:00
value, as shown in <xref linkend="sql-backslash-table">.
</para>
2008-06-27 00:24:42 +02:00
<table id="sql-backslash-table">
<title>Backslash Escape Sequences</title>
<tgroup cols="2">
<thead>
<row>
<entry>Backslash Escape Sequence</>
<entry>Interpretation</entry>
</row>
</thead>
<tbody>
<row>
<entry><literal>\b</literal></entry>
<entry>backspace</entry>
</row>
<row>
<entry><literal>\f</literal></entry>
<entry>form feed</entry>
</row>
<row>
<entry><literal>\n</literal></entry>
<entry>newline</entry>
</row>
<row>
<entry><literal>\r</literal></entry>
<entry>carriage return</entry>
</row>
<row>
<entry><literal>\t</literal></entry>
<entry>tab</entry>
</row>
<row>
<entry>
<literal>\<replaceable>o</replaceable></literal>,
<literal>\<replaceable>oo</replaceable></literal>,
<literal>\<replaceable>ooo</replaceable></literal>
(<replaceable>o</replaceable> = 0 - 7)
</entry>
<entry>octal byte value</entry>
</row>
<row>
<entry>
<literal>\x<replaceable>h</replaceable></literal>,
<literal>\x<replaceable>hh</replaceable></literal>
(<replaceable>h</replaceable> = 0 - 9, A - F)
</entry>
<entry>hexadecimal byte value</entry>
</row>
2009-09-23 01:52:53 +02:00
<row>
<entry>
<literal>\u<replaceable>xxxx</replaceable></literal>,
<literal>\U<replaceable>xxxxxxxx</replaceable></literal>
(<replaceable>x</replaceable> = 0 - 9, A - F)
</entry>
<entry>16 or 32-bit hexadecimal Unicode character value</entry>
</row>
2008-06-27 00:24:42 +02:00
</tbody>
</tgroup>
</table>
2008-10-29 09:04:54 +01:00
<para>
Any other
2006-10-21 19:12:07 +02:00
character following a backslash is taken literally. Thus, to
include a backslash character, write two backslashes (<literal>\\</>).
Also, a single quote can be included in an escape string by writing
<literal>\'</literal>, in addition to the normal way of <literal>''</>.
</para>
2008-10-29 09:04:54 +01:00
<para>
2009-09-23 01:52:53 +02:00
It is your responsibility that the byte sequences you create,
especially when using the octal or hexadecimal escapes, compose
2008-10-29 09:04:54 +01:00
valid characters in the server character set encoding. When the
2009-09-23 01:52:53 +02:00
server encoding is UTF-8, then the Unicode escapes or the
alternative Unicode escape syntax, explained
in <xref linkend="sql-syntax-strings-uescape">, should be used
instead. (The alternative would be doing the UTF-8 encoding by
hand and writing out the bytes, which would be very cumbersome.)
</para>
<para>
The Unicode escape syntax works fully only when the server
2010-09-07 20:54:09 +02:00
encoding is <literal>UTF8</>. When other server encodings are
used, only code points in the ASCII range (up
to <literal>\u007F</>) can be specified. Both the 4-digit and
the 8-digit form can be used to specify UTF-16 surrogate pairs to
compose characters with code points larger than U+FFFF, although
the availability of the 8-digit form technically makes this
unnecessary. (When surrogate pairs are used when the server
encoding is <literal>UTF8</>, they are first combined into a
single code point that is then encoded in UTF-8.)
2008-10-29 09:04:54 +01:00
</para>
2006-10-21 19:12:07 +02:00
<caution>
<para>
If the configuration parameter
<xref linkend="guc-standard-conforming-strings"> is <literal>off</>,
then <productname>PostgreSQL</productname> recognizes backslash escapes
2010-07-20 02:34:44 +02:00
in both regular and escape string constants. However, as of
<productname>PostgreSQL</> 9.1, the default is <literal>on</>, meaning
that backslash escapes are recognized only in escape string constants.
This behavior is more standards-compliant, but might break applications
which rely on the historical behavior, where backslash escapes
were always recognized. As a workaround, you can set this parameter
to <literal>off</>, but it is better to migrate away from using backslash
escapes. If you need to use a backslash escape to represent a special
character, write the string constant with an <literal>E</>.
2006-10-21 19:12:07 +02:00
</para>
<para>
In addition to <varname>standard_conforming_strings</>, the configuration
parameters <xref linkend="guc-escape-string-warning"> and
<xref linkend="guc-backslash-quote"> govern treatment of backslashes
in string constants.
</para>
</caution>
<para>
2009-06-17 23:58:49 +02:00
The character with the code zero cannot be in a string constant.
2006-10-21 19:12:07 +02:00
</para>
2001-01-06 12:58:56 +01:00
</sect3>
2008-10-29 09:04:54 +01:00
<sect3 id="sql-syntax-strings-uescape">
<title>String Constants with Unicode Escapes</title>
<indexterm zone="sql-syntax-strings-uescape">
<primary>Unicode escape</primary>
<secondary>in string constants</secondary>
</indexterm>
<para>
<productname>PostgreSQL</productname> also supports another type
of escape syntax for strings that allows specifying arbitrary
Unicode characters by code point. A Unicode escape string
2009-02-04 22:30:41 +01:00
constant starts with <literal>U&</literal> (upper or lower case
2008-10-29 09:04:54 +01:00
letter U followed by ampersand) immediately before the opening
quote, without any spaces in between, for
2009-02-04 22:30:41 +01:00
example <literal>U&'foo'</literal>. (Note that this creates an
ambiguity with the operator <literal>&</literal>. Use spaces
2008-10-29 09:04:54 +01:00
around the operator to avoid this problem.) Inside the quotes,
Unicode characters can be specified in escaped form by writing a
backslash followed by the four-digit hexadecimal code point
number or alternatively a backslash followed by a plus sign
followed by a six-digit hexadecimal code point number. For
example, the string <literal>'data'</literal> could be written as
<programlisting>
2009-02-04 22:30:41 +01:00
U&'d\0061t\+000061'
2008-10-29 09:04:54 +01:00
</programlisting>
The following less trivial example writes the Russian
word <quote>slon</quote> (elephant) in Cyrillic letters:
<programlisting>
2009-02-04 22:30:41 +01:00
U&'\0441\043B\043E\043D'
2008-10-29 09:04:54 +01:00
</programlisting>
</para>
<para>
If a different escape character than backslash is desired, it can
be specified using
the <literal>UESCAPE</literal><indexterm><primary>UESCAPE</primary></indexterm>
clause after the string, for example:
<programlisting>
2009-02-04 22:30:41 +01:00
U&'d!0061t!+000061' UESCAPE '!'
2008-10-29 09:04:54 +01:00
</programlisting>
The escape character can be any single character other than a
hexadecimal digit, the plus sign, a single quote, a double quote,
or a whitespace character.
</para>
<para>
The Unicode escape syntax works only when the server encoding is
2010-09-07 20:54:09 +02:00
<literal>UTF8</>. When other server encodings are used, only
code points in the ASCII range (up to <literal>\007F</literal>)
can be specified. Both the 4-digit and the 6-digit form can be
used to specify UTF-16 surrogate pairs to compose characters with
code points larger than U+FFFF, although the availability of the
6-digit form technically makes this unnecessary. (When surrogate
pairs are used when the server encoding is <literal>UTF8</>, they
are first combined into a single code point that is then encoded
in UTF-8.)
2008-10-29 09:04:54 +01:00
</para>
2009-05-05 20:32:17 +02:00
<para>
Also, the Unicode escape syntax for string constants only works
when the configuration
parameter <xref linkend="guc-standard-conforming-strings"> is
turned on. This is because otherwise this syntax could confuse
clients that parse the SQL statements to the point that it could
lead to SQL injections and similar security issues. If the
parameter is set to off, this syntax will be rejected with an
error message.
</para>
2008-10-29 09:04:54 +01:00
<para>
To include the escape character in the string literally, write it
twice.
</para>
</sect3>
2004-09-21 00:48:29 +02:00
<sect3 id="sql-syntax-dollar-quoting">
2011-02-01 23:00:26 +01:00
<title>Dollar-quoted String Constants</title>
2004-09-21 00:48:29 +02:00
<indexterm>
<primary>dollar quoting</primary>
</indexterm>
<para>
While the standard syntax for specifying string constants is usually
convenient, it can be difficult to understand when the desired string
contains many single quotes or backslashes, since each of those must
be doubled. To allow more readable queries in such situations,
<productname>PostgreSQL</productname> provides another way, called
<quote>dollar quoting</quote>, to write string constants.
A dollar-quoted string constant
consists of a dollar sign (<literal>$</literal>), an optional
<quote>tag</quote> of zero or more characters, another dollar
sign, an arbitrary sequence of characters that makes up the
string content, a dollar sign, the same tag that began this
dollar quote, and a dollar sign. For example, here are two
different ways to specify the string <quote>Dianne's horse</>
using dollar quoting:
<programlisting>
$$Dianne's horse$$
$SomeTag$Dianne's horse$SomeTag$
</programlisting>
Notice that inside the dollar-quoted string, single quotes can be
used without needing to be escaped. Indeed, no characters inside
a dollar-quoted string are ever escaped: the string content is always
written literally. Backslashes are not special, and neither are
dollar signs, unless they are part of a sequence matching the opening
tag.
</para>
<para>
It is possible to nest dollar-quoted string constants by choosing
different tags at each nesting level. This is most commonly used in
writing function definitions. For example:
<programlisting>
$function$
BEGIN
RETURN ($1 ~ $q$[\t\r\n\v\\]$q$);
END;
$function$
</programlisting>
Here, the sequence <literal>$q$[\t\r\n\v\\]$q$</> represents a
dollar-quoted literal string <literal>[\t\r\n\v\\]</>, which will
be recognized when the function body is executed by
<productname>PostgreSQL</>. But since the sequence does not match
the outer dollar quoting delimiter <literal>$function$</>, it is
just some more characters within the constant so far as the outer
string is concerned.
</para>
<para>
The tag, if any, of a dollar-quoted string follows the same rules
as an unquoted identifier, except that it cannot contain a dollar sign.
Tags are case sensitive, so <literal>$tag$String content$tag$</literal>
is correct, but <literal>$TAG$String content$tag$</literal> is not.
</para>
<para>
A dollar-quoted string that follows a keyword or identifier must
be separated from it by whitespace; otherwise the dollar quoting
delimiter would be taken as part of the preceding identifier.
</para>
<para>
Dollar quoting is not part of the SQL standard, but it is often a more
convenient way to write complicated string literals than the
standard-compliant single quote syntax. It is particularly useful when
representing string constants inside other constants, as is often needed
in procedural function definitions. With single-quote syntax, each
backslash in the above example would have to be written as four
backslashes, which would be reduced to two backslashes in parsing the
original string constant, and then to one when the inner string constant
is re-parsed during function execution.
</para>
</sect3>
2001-01-13 19:34:51 +01:00
<sect3 id="sql-syntax-bit-strings">
2011-02-01 23:00:26 +01:00
<title>Bit-string Constants</title>
1999-07-22 17:11:05 +02:00
2001-05-13 00:51:36 +02:00
<indexterm zone="sql-syntax-bit-strings">
2003-08-31 19:32:24 +02:00
<primary>bit string</primary>
<secondary>constant</secondary>
2001-05-13 00:51:36 +02:00
</indexterm>
1999-07-22 17:11:05 +02:00
<para>
2004-09-21 00:48:29 +02:00
Bit-string constants look like regular string constants with a
2001-01-06 12:58:56 +01:00
<literal>B</literal> (upper or lower case) immediately before the
opening quote (no intervening whitespace), e.g.,
<literal>B'1001'</literal>. The only characters allowed within
2002-01-07 03:29:15 +01:00
bit-string constants are <literal>0</literal> and
2002-10-20 07:05:46 +02:00
<literal>1</literal>.
1999-09-01 04:37:40 +02:00
</para>
1999-07-22 17:11:05 +02:00
2002-10-20 07:05:46 +02:00
<para>
Alternatively, bit-string constants can be specified in hexadecimal
notation, using a leading <literal>X</literal> (upper or lower case),
e.g., <literal>X'1FF'</literal>. This notation is equivalent to
2002-11-11 21:14:04 +01:00
a bit-string constant with four binary digits for each hexadecimal digit.
2002-10-20 07:05:46 +02:00
</para>
1999-07-22 17:11:05 +02:00
<para>
2002-10-20 07:05:46 +02:00
Both forms of bit-string constant can be continued
across lines in the same way as regular string constants.
2004-09-21 00:48:29 +02:00
Dollar quoting cannot be used in a bit-string constant.
2001-01-06 12:58:56 +01:00
</para>
</sect3>
1999-07-22 17:11:05 +02:00
2001-01-06 12:58:56 +01:00
<sect3>
2002-10-20 07:05:46 +02:00
<title>Numeric Constants</title>
1999-07-22 17:11:05 +02:00
2001-05-13 00:51:36 +02:00
<indexterm>
2003-08-31 19:32:24 +02:00
<primary>number</primary>
<secondary>constant</secondary>
2001-05-13 00:51:36 +02:00
</indexterm>
2001-01-06 12:58:56 +01:00
<para>
2002-10-20 07:05:46 +02:00
Numeric constants are accepted in these general forms:
2001-01-06 12:58:56 +01:00
<synopsis>
2002-10-20 07:05:46 +02:00
<replaceable>digits</replaceable>
2001-01-06 12:58:56 +01:00
<replaceable>digits</replaceable>.<optional><replaceable>digits</replaceable></optional><optional>e<optional>+-</optional><replaceable>digits</replaceable></optional>
<optional><replaceable>digits</replaceable></optional>.<replaceable>digits</replaceable><optional>e<optional>+-</optional><replaceable>digits</replaceable></optional>
<replaceable>digits</replaceable>e<optional>+-</optional><replaceable>digits</replaceable>
</synopsis>
where <replaceable>digits</replaceable> is one or more decimal
2002-10-20 07:05:46 +02:00
digits (0 through 9). At least one digit must be before or after the
decimal point, if one is used. At least one digit must follow the
exponent marker (<literal>e</literal>), if one is present.
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
There cannot be any spaces or other characters embedded in the
2002-11-11 21:14:04 +01:00
constant. Note that any leading plus or minus sign is not actually
2002-10-20 07:05:46 +02:00
considered part of the constant; it is an operator applied to the
constant.
1999-09-01 04:37:40 +02:00
</para>
2002-06-01 22:56:55 +02:00
<para>
2002-10-20 07:05:46 +02:00
These are some examples of valid numeric constants:
2002-06-01 22:56:55 +02:00
<literallayout>
2002-10-20 07:05:46 +02:00
42
2001-01-06 12:58:56 +01:00
3.5
4.
.001
5e2
1.925e-3
2002-06-01 22:56:55 +02:00
</literallayout>
</para>
2001-01-06 12:58:56 +01:00
1999-09-01 04:37:40 +02:00
<para>
2003-08-31 19:32:24 +02:00
<indexterm><primary>integer</primary></indexterm>
<indexterm><primary>bigint</primary></indexterm>
<indexterm><primary>numeric</primary></indexterm>
2002-10-20 07:05:46 +02:00
A numeric constant that contains neither a decimal point nor an
exponent is initially presumed to be type <type>integer</> if its
value fits in type <type>integer</> (32 bits); otherwise it is
presumed to be type <type>bigint</> if its
value fits in type <type>bigint</> (64 bits); otherwise it is
2004-09-21 00:48:29 +02:00
taken to be type <type>numeric</>. Constants that contain decimal
2002-10-20 07:05:46 +02:00
points and/or exponents are always initially presumed to be type
<type>numeric</>.
</para>
<para>
The initially assigned data type of a numeric constant is just a
2003-08-31 19:32:24 +02:00
starting point for the type resolution algorithms. In most cases
the constant will be automatically coerced to the most
appropriate type depending on context. When necessary, you can
force a numeric value to be interpreted as a specific data type
by casting it.<indexterm><primary>type cast</primary></indexterm>
For example, you can force a numeric value to be treated as type
2007-02-01 01:28:19 +01:00
<type>real</> (<type>float4</>) by writing:
1999-09-01 04:37:40 +02:00
2002-06-01 22:56:55 +02:00
<programlisting>
2001-01-06 12:58:56 +01:00
REAL '1.23' -- string style
2002-10-20 07:05:46 +02:00
1.23::REAL -- PostgreSQL (historical) style
2002-06-01 22:56:55 +02:00
</programlisting>
2004-09-21 00:48:29 +02:00
These are actually just special cases of the general casting
notations discussed next.
</para>
</sect3>
1999-07-22 17:11:05 +02:00
2001-01-26 23:04:22 +01:00
<sect3 id="sql-syntax-constants-generic">
2001-01-06 12:58:56 +01:00
<title>Constants of Other Types</title>
1999-07-22 17:11:05 +02:00
2001-05-13 00:51:36 +02:00
<indexterm>
2003-08-31 19:32:24 +02:00
<primary>data type</primary>
<secondary>constant</secondary>
2001-05-13 00:51:36 +02:00
</indexterm>
1999-07-22 17:11:05 +02:00
<para>
2001-01-06 12:58:56 +01:00
A constant of an <emphasis>arbitrary</emphasis> type can be
entered using any one of the following notations:
<synopsis>
1999-07-22 17:11:05 +02:00
<replaceable>type</replaceable> '<replaceable>string</replaceable>'
'<replaceable>string</replaceable>'::<replaceable>type</replaceable>
2000-08-07 21:53:27 +02:00
CAST ( '<replaceable>string</replaceable>' AS <replaceable>type</replaceable> )
2001-01-06 12:58:56 +01:00
</synopsis>
2004-09-21 00:48:29 +02:00
The string constant's text is passed to the input conversion
2001-01-06 12:58:56 +01:00
routine for the type called <replaceable>type</replaceable>. The
result is a constant of the indicated type. The explicit type
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
cast can be omitted if there is no ambiguity as to the type the
2004-09-21 00:48:29 +02:00
constant must be (for example, when it is assigned directly to a
table column), in which case it is automatically coerced.
</para>
<para>
The string constant can be written using either regular SQL
notation or dollar-quoting.
1999-07-22 17:11:05 +02:00
</para>
2000-12-17 06:47:57 +01:00
<para>
It is also possible to specify a type coercion using a function-like
syntax:
2001-01-06 12:58:56 +01:00
<synopsis>
2002-01-10 00:38:06 +01:00
<replaceable>typename</replaceable> ( '<replaceable>string</replaceable>' )
2001-01-06 12:58:56 +01:00
</synopsis>
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
but not all type names can be used in this way; see <xref
2002-01-10 00:38:06 +01:00
linkend="sql-syntax-type-casts"> for details.
2000-12-17 06:47:57 +01:00
</para>
<para>
2001-01-06 12:58:56 +01:00
The <literal>::</literal>, <literal>CAST()</literal>, and
2002-03-22 20:20:45 +01:00
function-call syntaxes can also be used to specify run-time type
2002-01-10 00:38:06 +01:00
conversions of arbitrary expressions, as discussed in <xref
2007-06-05 23:31:09 +02:00
linkend="sql-syntax-type-casts">. To avoid syntactic ambiguity, the
<literal><replaceable>type</> '<replaceable>string</>'</literal>
syntax can only be used to specify the type of a simple literal constant.
Another restriction on the
<literal><replaceable>type</> '<replaceable>string</>'</literal>
syntax is that it does not work for array types; use <literal>::</literal>
2002-01-10 00:38:06 +01:00
or <literal>CAST()</literal> to specify the type of an array constant.
2000-12-17 06:47:57 +01:00
</para>
2005-10-23 21:29:49 +02:00
<para>
The <literal>CAST()</> syntax conforms to SQL. The
2007-06-05 23:31:09 +02:00
<literal><replaceable>type</> '<replaceable>string</>'</literal>
2005-10-23 21:29:49 +02:00
syntax is a generalization of the standard: SQL specifies this syntax only
2005-11-05 00:14:02 +01:00
for a few data types, but <productname>PostgreSQL</productname> allows it
2005-10-23 21:29:49 +02:00
for all types. The syntax with
<literal>::</literal> is historical <productname>PostgreSQL</productname>
usage, as is the function-call syntax.
</para>
2001-01-06 12:58:56 +01:00
</sect3>
</sect2>
<sect2 id="sql-syntax-operators">
<title>Operators</title>
2001-05-13 00:51:36 +02:00
<indexterm zone="sql-syntax-operators">
2003-08-31 19:32:24 +02:00
<primary>operator</primary>
2001-05-13 00:51:36 +02:00
<secondary>syntax</secondary>
</indexterm>
2001-01-06 12:58:56 +01:00
<para>
2003-11-04 20:18:15 +01:00
An operator name is a sequence of up to <symbol>NAMEDATALEN</symbol>-1
2002-08-23 06:27:19 +02:00
(63 by default) characters from the following list:
2001-01-06 12:58:56 +01:00
<literallayout>
2003-06-20 01:22:40 +02:00
+ - * / < > = ~ ! @ # % ^ & | ` ?
2001-01-06 12:58:56 +01:00
</literallayout>
There are a few restrictions on operator names, however:
<itemizedlist>
<listitem>
<para>
<literal>--</literal> and <literal>/*</literal> cannot appear
anywhere in an operator name, since they will be taken as the
start of a comment.
</para>
</listitem>
<listitem>
<para>
2001-09-13 17:55:24 +02:00
A multiple-character operator name cannot end in <literal>+</> or <literal>-</>,
2001-01-06 12:58:56 +01:00
unless the name also contains at least one of these characters:
<literallayout>
2003-06-20 01:22:40 +02:00
~ ! @ # % ^ & | ` ?
2001-01-06 12:58:56 +01:00
</literallayout>
For example, <literal>@-</literal> is an allowed operator name,
but <literal>*-</literal> is not. This restriction allows
2001-11-21 07:09:45 +01:00
<productname>PostgreSQL</productname> to parse SQL-compliant
2001-01-06 12:58:56 +01:00
queries without requiring spaces between tokens.
</para>
</listitem>
</itemizedlist>
</para>
<para>
When working with non-SQL-standard operator names, you will usually
need to separate adjacent operators with spaces to avoid ambiguity.
2002-01-07 03:29:15 +01:00
For example, if you have defined a left unary operator named <literal>@</literal>,
2001-01-06 12:58:56 +01:00
you cannot write <literal>X*@Y</literal>; you must write
<literal>X* @Y</literal> to ensure that
2001-11-21 07:09:45 +01:00
<productname>PostgreSQL</productname> reads it as two operator names
2001-01-06 12:58:56 +01:00
not one.
</para>
</sect2>
<sect2>
<title>Special Characters</title>
<para>
Some characters that are not alphanumeric have a special meaning
that is different from being an operator. Details on the usage can
be found at the location where the respective syntax element is
described. This section only exists to advise the existence and
summarize the purposes of these characters.
<itemizedlist>
<listitem>
<para>
A dollar sign (<literal>$</literal>) followed by digits is used
2003-06-20 01:22:40 +02:00
to represent a positional parameter in the body of a function
2003-02-19 04:13:25 +01:00
definition or a prepared statement. In other contexts the
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
dollar sign can be part of an identifier or a dollar-quoted string
2004-12-23 06:37:40 +01:00
constant.
2001-01-06 12:58:56 +01:00
</para>
</listitem>
<listitem>
<para>
Parentheses (<literal>()</literal>) have their usual meaning to
group expressions and enforce precedence. In some cases
parentheses are required as part of the fixed syntax of a
particular SQL command.
</para>
</listitem>
<listitem>
<para>
Brackets (<literal>[]</literal>) are used to select the elements
of an array. See <xref linkend="arrays"> for more information
on arrays.
</para>
</listitem>
<listitem>
<para>
Commas (<literal>,</literal>) are used in some syntactical
constructs to separate the elements of a list.
</para>
</listitem>
<listitem>
<para>
The semicolon (<literal>;</literal>) terminates an SQL command.
2001-02-10 08:08:44 +01:00
It cannot appear anywhere within a command, except within a
string constant or quoted identifier.
2001-01-06 12:58:56 +01:00
</para>
</listitem>
<listitem>
<para>
The colon (<literal>:</literal>) is used to select
<quote>slices</quote> from arrays. (See <xref
linkend="arrays">.) In certain SQL dialects (such as Embedded
SQL), the colon is used to prefix variable names.
</para>
</listitem>
<listitem>
<para>
2004-12-23 06:37:40 +01:00
The asterisk (<literal>*</literal>) is used in some contexts to denote
all the fields of a table row or composite value. It also
2006-07-27 21:52:07 +02:00
has a special meaning when used as the argument of an
aggregate function, namely that the aggregate does not require
any explicit parameter.
2001-01-06 12:58:56 +01:00
</para>
</listitem>
<listitem>
<para>
2003-03-13 02:30:29 +01:00
The period (<literal>.</literal>) is used in numeric
2002-09-13 00:05:36 +02:00
constants, and to separate schema, table, and column names.
2001-01-06 12:58:56 +01:00
</para>
</listitem>
</itemizedlist>
</para>
</sect2>
<sect2 id="sql-syntax-comments">
<title>Comments</title>
2001-05-13 00:51:36 +02:00
<indexterm zone="sql-syntax-comments">
2003-08-31 19:32:24 +02:00
<primary>comment</primary>
<secondary sortas="SQL">in SQL</secondary>
2001-05-13 00:51:36 +02:00
</indexterm>
2001-01-06 12:58:56 +01:00
<para>
2009-04-27 18:27:36 +02:00
A comment is a sequence of characters beginning with
2001-01-06 12:58:56 +01:00
double dashes and extending to the end of the line, e.g.:
<programlisting>
2003-11-04 10:55:39 +01:00
-- This is a standard SQL comment
2001-01-06 12:58:56 +01:00
</programlisting>
</para>
<para>
Alternatively, C-style block comments can be used:
<programlisting>
2001-09-09 19:21:59 +02:00
/* multiline comment
2001-01-06 12:58:56 +01:00
* with nesting: /* nested block comment */
*/
</programlisting>
where the comment begins with <literal>/*</literal> and extends to
the matching occurrence of <literal>*/</literal>. These block
2003-11-04 10:55:39 +01:00
comments nest, as specified in the SQL standard but unlike C, so that one can
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
comment out larger blocks of code that might contain existing block
2001-01-06 12:58:56 +01:00
comments.
</para>
<para>
2009-06-17 23:58:49 +02:00
A comment is removed from the input stream before further syntax
analysis and is effectively replaced by whitespace.
2001-01-06 12:58:56 +01:00
</para>
</sect2>
2002-06-01 22:56:55 +02:00
<sect2 id="sql-precedence">
<title>Lexical Precedence</title>
<indexterm zone="sql-precedence">
2003-08-31 19:32:24 +02:00
<primary>operator</primary>
2002-06-01 22:56:55 +02:00
<secondary>precedence</secondary>
</indexterm>
<para>
2002-11-11 21:14:04 +01:00
<xref linkend="sql-precedence-table"> shows the precedence and
2002-11-15 04:11:18 +01:00
associativity of the operators in <productname>PostgreSQL</>.
Most operators have the same precedence and are left-associative.
The precedence and associativity of the operators is hard-wired
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
into the parser. This can lead to non-intuitive behavior; for
2002-11-15 04:11:18 +01:00
example the Boolean operators <literal><</> and
<literal>></> have a different precedence than the Boolean
operators <literal><=</> and <literal>>=</>. Also, you will
sometimes need to add parentheses when using combinations of
2007-02-01 01:28:19 +01:00
binary and unary operators. For instance:
2002-06-01 22:56:55 +02:00
<programlisting>
SELECT 5 ! - 6;
</programlisting>
2007-02-01 01:28:19 +01:00
will be parsed as:
2002-06-01 22:56:55 +02:00
<programlisting>
SELECT 5 ! (- 6);
</programlisting>
2004-11-15 07:32:15 +01:00
because the parser has no idea — until it is too late
— that <token>!</token> is defined as a postfix operator,
not an infix one. To get the desired behavior in this case, you
2007-02-01 01:28:19 +01:00
must write:
2002-06-01 22:56:55 +02:00
<programlisting>
SELECT (5 !) - 6;
</programlisting>
This is the price one pays for extensibility.
</para>
2002-11-11 21:14:04 +01:00
<table id="sql-precedence-table">
2002-06-01 22:56:55 +02:00
<title>Operator Precedence (decreasing)</title>
<tgroup cols="3">
<thead>
<row>
<entry>Operator/Element</entry>
<entry>Associativity</entry>
<entry>Description</entry>
</row>
</thead>
<tbody>
<row>
<entry><token>.</token></entry>
<entry>left</entry>
<entry>table/column name separator</entry>
</row>
<row>
<entry><token>::</token></entry>
<entry>left</entry>
<entry><productname>PostgreSQL</productname>-style typecast</entry>
</row>
<row>
<entry><token>[</token> <token>]</token></entry>
<entry>left</entry>
<entry>array element selection</entry>
</row>
<row>
<entry><token>-</token></entry>
<entry>right</entry>
<entry>unary minus</entry>
</row>
<row>
<entry><token>^</token></entry>
<entry>left</entry>
<entry>exponentiation</entry>
</row>
<row>
<entry><token>*</token> <token>/</token> <token>%</token></entry>
<entry>left</entry>
<entry>multiplication, division, modulo</entry>
</row>
<row>
<entry><token>+</token> <token>-</token></entry>
<entry>left</entry>
<entry>addition, subtraction</entry>
</row>
<row>
<entry><token>IS</token></entry>
<entry></entry>
2007-02-20 15:04:50 +01:00
<entry><literal>IS TRUE</>, <literal>IS FALSE</>, <literal>IS UNKNOWN</>, <literal>IS NULL</></entry>
2002-06-01 22:56:55 +02:00
</row>
<row>
<entry><token>ISNULL</token></entry>
<entry></entry>
2002-09-21 20:32:54 +02:00
<entry>test for null</entry>
2002-06-01 22:56:55 +02:00
</row>
<row>
<entry><token>NOTNULL</token></entry>
<entry></entry>
2002-09-21 20:32:54 +02:00
<entry>test for not null</entry>
2002-06-01 22:56:55 +02:00
</row>
<row>
<entry>(any other)</entry>
<entry>left</entry>
<entry>all other native and user-defined operators</entry>
</row>
<row>
<entry><token>IN</token></entry>
<entry></entry>
<entry>set membership</entry>
</row>
<row>
<entry><token>BETWEEN</token></entry>
<entry></entry>
2004-12-23 06:37:40 +01:00
<entry>range containment</entry>
2002-06-01 22:56:55 +02:00
</row>
<row>
<entry><token>OVERLAPS</token></entry>
<entry></entry>
<entry>time interval overlap</entry>
</row>
<row>
2002-08-10 21:01:53 +02:00
<entry><token>LIKE</token> <token>ILIKE</token> <token>SIMILAR</token></entry>
2002-06-01 22:56:55 +02:00
<entry></entry>
<entry>string pattern matching</entry>
</row>
<row>
<entry><token><</token> <token>></token></entry>
<entry></entry>
<entry>less than, greater than</entry>
</row>
<row>
<entry><token>=</token></entry>
<entry>right</entry>
<entry>equality, assignment</entry>
</row>
<row>
<entry><token>NOT</token></entry>
<entry>right</entry>
<entry>logical negation</entry>
</row>
<row>
<entry><token>AND</token></entry>
<entry>left</entry>
<entry>logical conjunction</entry>
</row>
<row>
<entry><token>OR</token></entry>
<entry>left</entry>
<entry>logical disjunction</entry>
</row>
</tbody>
</tgroup>
</table>
<para>
Note that the operator precedence rules also apply to user-defined
operators that have the same names as the built-in operators
mentioned above. For example, if you define a
<quote>+</quote> operator for some custom data type it will have
the same precedence as the built-in <quote>+</quote> operator, no
matter what yours does.
</para>
2002-08-10 21:01:53 +02:00
<para>
When a schema-qualified operator name is used in the
2007-02-01 01:28:19 +01:00
<literal>OPERATOR</> syntax, as for example in:
2002-08-10 21:01:53 +02:00
<programlisting>
SELECT 3 OPERATOR(pg_catalog.+) 4;
</programlisting>
the <literal>OPERATOR</> construct is taken to have the default precedence
2002-11-11 21:14:04 +01:00
shown in <xref linkend="sql-precedence-table"> for <quote>any other</> operator. This is true no matter
2009-04-27 18:27:36 +02:00
which specific operator appears inside <literal>OPERATOR()</>.
2002-08-10 21:01:53 +02:00
</para>
2002-06-01 22:56:55 +02:00
</sect2>
2001-01-06 12:58:56 +01:00
</sect1>
2001-01-21 23:02:01 +01:00
<sect1 id="sql-expressions">
<title>Value Expressions</title>
1999-07-22 17:11:05 +02:00
2003-08-31 19:32:24 +02:00
<indexterm zone="sql-expressions">
<primary>expression</primary>
<secondary>syntax</secondary>
</indexterm>
<indexterm zone="sql-expressions">
<primary>value expression</primary>
</indexterm>
<indexterm>
<primary>scalar</primary>
<see>expression</see>
</indexterm>
2001-01-21 23:02:01 +01:00
<para>
2001-02-10 08:08:44 +01:00
Value expressions are used in a variety of contexts, such
2001-01-21 23:02:01 +01:00
as in the target list of the <command>SELECT</command> command, as
new column values in <command>INSERT</command> or
<command>UPDATE</command>, or in search conditions in a number of
commands. The result of a value expression is sometimes called a
<firstterm>scalar</firstterm>, to distinguish it from the result of
a table expression (which is a table). Value expressions are
therefore also called <firstterm>scalar expressions</firstterm> (or
even simply <firstterm>expressions</firstterm>). The expression
syntax allows the calculation of values from primitive parts using
arithmetic, logical, set, and other operations.
</para>
1999-05-12 09:32:47 +02:00
2001-01-21 23:02:01 +01:00
<para>
A value expression is one of the following:
1999-05-12 09:32:47 +02:00
2001-01-21 23:02:01 +01:00
<itemizedlist>
<listitem>
<para>
2009-04-27 18:27:36 +02:00
A constant or literal value
2001-01-21 23:02:01 +01:00
</para>
</listitem>
1999-07-22 17:11:05 +02:00
2001-01-21 23:02:01 +01:00
<listitem>
<para>
2009-04-27 18:27:36 +02:00
A column reference
2001-01-21 23:02:01 +01:00
</para>
</listitem>
1999-07-22 17:11:05 +02:00
2001-01-21 23:02:01 +01:00
<listitem>
<para>
2003-08-10 00:50:22 +02:00
A positional parameter reference, in the body of a function definition
2009-04-27 18:27:36 +02:00
or prepared statement
2001-01-21 23:02:01 +01:00
</para>
</listitem>
1999-07-22 17:11:05 +02:00
2003-11-04 20:18:15 +01:00
<listitem>
<para>
2009-04-27 18:27:36 +02:00
A subscripted expression
2003-11-04 20:18:15 +01:00
</para>
</listitem>
<listitem>
<para>
2009-04-27 18:27:36 +02:00
A field selection expression
2003-11-04 20:18:15 +01:00
</para>
</listitem>
2001-01-21 23:02:01 +01:00
<listitem>
2001-10-09 20:46:00 +02:00
<para>
2009-04-27 18:27:36 +02:00
An operator invocation
2001-01-21 23:02:01 +01:00
</para>
</listitem>
1999-07-22 17:11:05 +02:00
2001-01-21 23:02:01 +01:00
<listitem>
<para>
2009-04-27 18:27:36 +02:00
A function call
2001-01-21 23:02:01 +01:00
</para>
</listitem>
1999-07-22 17:11:05 +02:00
2001-01-21 23:02:01 +01:00
<listitem>
<para>
2009-04-27 18:27:36 +02:00
An aggregate expression
2001-01-21 23:02:01 +01:00
</para>
</listitem>
1999-07-22 17:11:05 +02:00
2008-12-28 19:54:01 +01:00
<listitem>
<para>
2009-04-27 18:27:36 +02:00
A window function call
2008-12-28 19:54:01 +01:00
</para>
</listitem>
2001-01-21 23:02:01 +01:00
<listitem>
<para>
2009-04-27 18:27:36 +02:00
A type cast
2001-01-21 23:02:01 +01:00
</para>
</listitem>
1999-07-22 17:11:05 +02:00
2011-03-09 04:50:15 +01:00
<listitem>
<para>
A collation expression
</para>
</listitem>
2001-01-21 23:02:01 +01:00
<listitem>
<para>
2009-04-27 18:27:36 +02:00
A scalar subquery
2002-01-10 00:38:06 +01:00
</para>
</listitem>
2003-08-10 00:50:22 +02:00
<listitem>
<para>
2009-04-27 18:27:36 +02:00
An array constructor
2003-08-10 00:50:22 +02:00
</para>
</listitem>
2004-05-11 00:44:49 +02:00
<listitem>
<para>
2009-04-27 18:27:36 +02:00
A row constructor
2004-05-11 00:44:49 +02:00
</para>
</listitem>
2002-01-10 00:38:06 +01:00
<listitem>
<para>
2009-06-17 23:58:49 +02:00
Another value expression in parentheses (used to group
2003-08-31 19:32:24 +02:00
subexpressions and override
2009-06-17 23:58:49 +02:00
precedence<indexterm><primary>parenthesis</></>)
2001-01-21 23:02:01 +01:00
</para>
</listitem>
</itemizedlist>
</para>
1999-07-22 17:11:05 +02:00
2001-01-21 23:02:01 +01:00
<para>
2001-01-23 00:34:33 +01:00
In addition to this list, there are a number of constructs that can
2001-01-21 23:02:01 +01:00
be classified as an expression but do not follow any general syntax
rules. These generally have the semantics of a function or
operator and are explained in the appropriate location in <xref
linkend="functions">. An example is the <literal>IS NULL</literal>
clause.
</para>
1999-07-22 17:11:05 +02:00
2001-01-21 23:02:01 +01:00
<para>
We have already discussed constants in <xref
linkend="sql-syntax-constants">. The following sections discuss
the remaining options.
</para>
1999-07-22 17:11:05 +02:00
2001-01-21 23:02:01 +01:00
<sect2>
<title>Column References</title>
1999-07-22 17:11:05 +02:00
2003-08-31 19:32:24 +02:00
<indexterm>
<primary>column reference</primary>
</indexterm>
2001-01-21 23:02:01 +01:00
<para>
2009-04-27 18:27:36 +02:00
A column can be referenced in the form:
2001-01-21 23:02:01 +01:00
<synopsis>
2002-11-11 21:14:04 +01:00
<replaceable>correlation</replaceable>.<replaceable>columnname</replaceable>
2001-01-21 23:02:01 +01:00
</synopsis>
2002-11-11 21:14:04 +01:00
</para>
1999-07-22 17:11:05 +02:00
2002-11-11 21:14:04 +01:00
<para>
2002-04-25 22:14:43 +02:00
<replaceable>correlation</replaceable> is the name of a
2003-11-04 20:18:15 +01:00
table (possibly qualified with a schema name), or an alias for a table
2009-11-06 00:24:27 +01:00
defined by means of a <literal>FROM</literal> clause.
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
The correlation name and separating dot can be omitted if the column name
2002-11-11 21:14:04 +01:00
is unique across all the tables being used in the current query. (See also <xref linkend="queries">.)
</para>
2001-01-21 23:02:01 +01:00
</sect2>
1999-07-22 17:11:05 +02:00
2001-01-21 23:02:01 +01:00
<sect2>
<title>Positional Parameters</title>
1999-12-13 18:39:38 +01:00
2003-08-31 19:32:24 +02:00
<indexterm>
<primary>parameter</primary>
<secondary>syntax</secondary>
</indexterm>
<indexterm>
<primary>$</primary>
</indexterm>
2001-01-21 23:02:01 +01:00
<para>
2003-06-20 01:22:40 +02:00
A positional parameter reference is used to indicate a value
2002-10-20 07:05:46 +02:00
that is supplied externally to an SQL statement. Parameters are
2003-06-20 01:22:40 +02:00
used in SQL function definitions and in prepared queries. Some
client libraries also support specifying data values separately
from the SQL command string, in which case parameters are used to
refer to the out-of-line data values.
2002-10-20 07:05:46 +02:00
The form of a parameter reference is:
2001-01-21 23:02:01 +01:00
<synopsis>
$<replaceable>number</replaceable>
</synopsis>
</para>
1999-07-22 17:11:05 +02:00
2001-01-21 23:02:01 +01:00
<para>
For example, consider the definition of a function,
2007-02-01 01:28:19 +01:00
<function>dept</function>, as:
1999-12-13 18:39:38 +01:00
2001-01-21 23:02:01 +01:00
<programlisting>
2002-11-11 21:14:04 +01:00
CREATE FUNCTION dept(text) RETURNS dept
2004-12-23 06:37:40 +01:00
AS $$ SELECT * FROM dept WHERE name = $1 $$
2002-11-11 21:14:04 +01:00
LANGUAGE SQL;
2001-01-21 23:02:01 +01:00
</programlisting>
1999-07-22 17:11:05 +02:00
2005-10-23 21:29:49 +02:00
Here the <literal>$1</literal> references the value of the first
function argument whenever the function is invoked.
2001-01-21 23:02:01 +01:00
</para>
</sect2>
1999-07-22 17:11:05 +02:00
2003-11-04 20:18:15 +01:00
<sect2>
<title>Subscripts</title>
<indexterm>
<primary>subscript</primary>
</indexterm>
<para>
If an expression yields a value of an array type, then a specific
element of the array value can be extracted by writing
<synopsis>
<replaceable>expression</replaceable>[<replaceable>subscript</replaceable>]
</synopsis>
or multiple adjacent elements (an <quote>array slice</>) can be extracted
by writing
<synopsis>
<replaceable>expression</replaceable>[<replaceable>lower_subscript</replaceable>:<replaceable>upper_subscript</replaceable>]
</synopsis>
(Here, the brackets <literal>[ ]</literal> are meant to appear literally.)
Each <replaceable>subscript</replaceable> is itself an expression,
which must yield an integer value.
</para>
<para>
In general the array <replaceable>expression</replaceable> must be
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
parenthesized, but the parentheses can be omitted when the expression
2003-11-04 20:18:15 +01:00
to be subscripted is just a column reference or positional parameter.
Also, multiple subscripts can be concatenated when the original array
2005-11-05 00:14:02 +01:00
is multidimensional.
2007-02-01 01:28:19 +01:00
For example:
2003-11-04 20:18:15 +01:00
<programlisting>
mytable.arraycolumn[4]
mytable.two_d_column[17][34]
$1[10:42]
(arrayfunction(a,b))[42]
</programlisting>
The parentheses in the last example are required.
See <xref linkend="arrays"> for more about arrays.
</para>
</sect2>
2011-03-20 04:58:53 +01:00
<sect2 id="field-selection">
2003-11-04 20:18:15 +01:00
<title>Field Selection</title>
<indexterm>
<primary>field selection</primary>
</indexterm>
<para>
If an expression yields a value of a composite type (row type), then a
specific field of the row can be extracted by writing
<synopsis>
<replaceable>expression</replaceable>.<replaceable>fieldname</replaceable>
</synopsis>
</para>
<para>
In general the row <replaceable>expression</replaceable> must be
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
parenthesized, but the parentheses can be omitted when the expression
2003-11-04 20:18:15 +01:00
to be selected from is just a table reference or positional parameter.
2007-02-01 01:28:19 +01:00
For example:
2003-11-04 20:18:15 +01:00
<programlisting>
mytable.mycolumn
$1.somecolumn
(rowfunction(a,b)).col3
</programlisting>
(Thus, a qualified column reference is actually just a special case
2008-12-09 21:52:03 +01:00
of the field selection syntax.) An important special case is
extracting a field from a table column that is of a composite type:
<programlisting>
(compositecol).somefield
(mytable.compositecol).somefield
</programlisting>
The parentheses are required here to show that
<structfield>compositecol</> is a column name not a table name,
or that <structname>mytable</> is a table name not a schema name
in the second case.
2003-11-04 20:18:15 +01:00
</para>
2010-10-14 19:07:13 +02:00
<para>
In a select list (see <xref linkend="queries-select-lists">), you
can ask for all fields of a composite value by
writing <literal>.*</literal>:
<programlisting>
(compositecol).*
</programlisting>
</para>
2003-11-04 20:18:15 +01:00
</sect2>
2002-01-10 00:38:06 +01:00
<sect2>
<title>Operator Invocations</title>
2003-08-31 19:32:24 +02:00
<indexterm>
<primary>operator</primary>
<secondary>invocation</secondary>
</indexterm>
2002-01-10 00:38:06 +01:00
<para>
There are three possible syntaxes for an operator invocation:
<simplelist>
<member><replaceable>expression</replaceable> <replaceable>operator</replaceable> <replaceable>expression</replaceable> (binary infix operator)</member>
<member><replaceable>operator</replaceable> <replaceable>expression</replaceable> (unary prefix operator)</member>
<member><replaceable>expression</replaceable> <replaceable>operator</replaceable> (unary postfix operator)</member>
</simplelist>
where the <replaceable>operator</replaceable> token follows the syntax
2002-04-25 22:14:43 +02:00
rules of <xref linkend="sql-syntax-operators">, or is one of the
2003-11-01 02:56:29 +01:00
key words <token>AND</token>, <token>OR</token>, and
2009-04-27 18:27:36 +02:00
<token>NOT</token>, or is a qualified operator name in the form:
2002-04-25 22:14:43 +02:00
<synopsis>
2002-11-11 21:14:04 +01:00
<literal>OPERATOR(</><replaceable>schema</><literal>.</><replaceable>operatorname</><literal>)</>
2002-04-25 22:14:43 +02:00
</synopsis>
Which particular operators exist and whether
2002-01-10 00:38:06 +01:00
they are unary or binary depends on what operators have been
defined by the system or the user. <xref linkend="functions">
describes the built-in operators.
</para>
</sect2>
2001-01-21 23:02:01 +01:00
<sect2>
<title>Function Calls</title>
1999-07-22 17:11:05 +02:00
2003-08-31 19:32:24 +02:00
<indexterm>
<primary>function</primary>
<secondary>invocation</secondary>
</indexterm>
2001-01-21 23:02:01 +01:00
<para>
2001-02-10 08:08:44 +01:00
The syntax for a function call is the name of a function
2002-04-25 22:14:43 +02:00
(possibly qualified with a schema name), followed by its argument list
2001-01-21 23:02:01 +01:00
enclosed in parentheses:
1999-07-22 17:11:05 +02:00
2001-01-21 23:02:01 +01:00
<synopsis>
2008-12-28 19:54:01 +01:00
<replaceable>function_name</replaceable> (<optional><replaceable>expression</replaceable> <optional>, <replaceable>expression</replaceable> ... </optional></optional> )
2001-01-21 23:02:01 +01:00
</synopsis>
</para>
1999-07-22 17:11:05 +02:00
2001-01-21 23:02:01 +01:00
<para>
For example, the following computes the square root of 2:
<programlisting>
sqrt(2)
</programlisting>
</para>
1999-07-22 17:11:05 +02:00
2001-01-21 23:02:01 +01:00
<para>
The list of built-in functions is in <xref linkend="functions">.
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
Other functions can be added by the user.
2001-01-21 23:02:01 +01:00
</para>
2009-10-08 04:39:25 +02:00
<para>
The arguments can optionally have names attached.
See <xref linkend="sql-syntax-calling-funcs"> for details.
</para>
2010-11-07 19:03:19 +01:00
<note>
<para>
A function that takes a single argument of composite type can
optionally be called using field-selection syntax, and conversely
field selection can be written in functional style. That is, the
notations <literal>col(table)</> and <literal>table.col</> are
interchangeable. This behavior is not SQL-standard but is provided
in <productname>PostgreSQL</> because it allows use of functions to
emulate <quote>computed fields</>. For more information see
<xref linkend="xfunc-sql-composite-functions">.
</para>
</note>
2001-01-21 23:02:01 +01:00
</sect2>
1999-07-22 17:11:05 +02:00
2001-01-21 23:02:01 +01:00
<sect2 id="syntax-aggregates">
<title>Aggregate Expressions</title>
1999-07-22 17:11:05 +02:00
2001-05-13 00:51:36 +02:00
<indexterm zone="syntax-aggregates">
2003-08-31 19:32:24 +02:00
<primary>aggregate function</primary>
<secondary>invocation</secondary>
2001-05-13 00:51:36 +02:00
</indexterm>
2001-01-21 23:02:01 +01:00
<para>
An <firstterm>aggregate expression</firstterm> represents the
application of an aggregate function across the rows selected by a
query. An aggregate function reduces multiple inputs to a single
output value, such as the sum or average of the inputs. The
syntax of an aggregate expression is one of the following:
2000-12-17 06:47:57 +01:00
2002-11-11 21:14:04 +01:00
<synopsis>
2009-12-15 18:57:48 +01:00
<replaceable>aggregate_name</replaceable> (<replaceable>expression</replaceable> [ , ... ] [ <replaceable>order_by_clause</replaceable> ] )
<replaceable>aggregate_name</replaceable> (ALL <replaceable>expression</replaceable> [ , ... ] [ <replaceable>order_by_clause</replaceable> ] )
<replaceable>aggregate_name</replaceable> (DISTINCT <replaceable>expression</replaceable> [ , ... ] [ <replaceable>order_by_clause</replaceable> ] )
2002-11-11 21:14:04 +01:00
<replaceable>aggregate_name</replaceable> ( * )
</synopsis>
2000-12-17 06:47:57 +01:00
2001-01-21 23:02:01 +01:00
where <replaceable>aggregate_name</replaceable> is a previously
2009-12-15 18:57:48 +01:00
defined aggregate (possibly qualified with a schema name),
2008-03-20 22:42:48 +01:00
<replaceable>expression</replaceable> is
2002-01-10 00:38:06 +01:00
any value expression that does not itself contain an aggregate
2009-12-15 18:57:48 +01:00
expression or a window function call, and
<replaceable>order_by_clause</replaceable> is a optional
<literal>ORDER BY</> clause as described below.
2001-01-21 23:02:01 +01:00
</para>
2000-12-17 06:47:57 +01:00
2001-01-21 23:02:01 +01:00
<para>
The first form of aggregate expression invokes the aggregate
2010-09-01 20:22:29 +02:00
once for each input row.
2001-02-10 08:08:44 +01:00
The second form is the same as the first, since
2010-09-01 20:22:29 +02:00
<literal>ALL</literal> is the default.
The third form invokes the aggregate once for each distinct value
of the expression (or distinct set of values, for multiple expressions)
found in the input rows.
The last form invokes the aggregate once for each input row; since no
2001-01-21 23:02:01 +01:00
particular input value is specified, it is generally only useful
2006-07-27 21:52:07 +02:00
for the <function>count(*)</function> aggregate function.
2001-01-21 23:02:01 +01:00
</para>
2000-12-17 06:47:57 +01:00
2010-09-01 20:22:29 +02:00
<para>
Most aggregate functions ignore null inputs, so that rows in which
one or more of the expression(s) yield null are discarded. This
can be assumed to be true, unless otherwise specified, for all
built-in aggregates.
</para>
2001-01-21 23:02:01 +01:00
<para>
For example, <literal>count(*)</literal> yields the total number
of input rows; <literal>count(f1)</literal> yields the number of
2010-09-01 20:22:29 +02:00
input rows in which <literal>f1</literal> is non-null, since
<function>count</> ignores nulls; and
2001-01-21 23:02:01 +01:00
<literal>count(distinct f1)</literal> yields the number of
2002-09-21 20:32:54 +02:00
distinct non-null values of <literal>f1</literal>.
2001-01-21 23:02:01 +01:00
</para>
1999-07-22 17:11:05 +02:00
2009-12-15 18:57:48 +01:00
<para>
Ordinarily, the input rows are fed to the aggregate function in an
unspecified order. In many cases this does not matter; for example,
<function>min</> produces the same result no matter what order it
receives the inputs in. However, some aggregate functions
2010-08-04 17:27:57 +02:00
(such as <function>array_agg</> and <function>string_agg</>) produce
2009-12-15 18:57:48 +01:00
results that depend on the ordering of the input rows. When using
such an aggregate, the optional <replaceable>order_by_clause</> can be
used to specify the desired ordering. The <replaceable>order_by_clause</>
has the same syntax as for a query-level <literal>ORDER BY</> clause, as
described in <xref linkend="queries-order">, except that its expressions
are always just expressions and cannot be output-column names or numbers.
For example:
<programlisting>
SELECT array_agg(a ORDER BY b DESC) FROM table;
</programlisting>
</para>
2010-08-04 17:27:57 +02:00
<para>
When dealing with multiple-argument aggregate functions, note that the
<literal>ORDER BY</> clause goes after all the aggregate arguments.
2010-08-05 20:21:19 +02:00
For example, write this:
2010-08-04 17:27:57 +02:00
<programlisting>
SELECT string_agg(a, ',' ORDER BY a) FROM table;
</programlisting>
not this:
<programlisting>
2010-08-05 20:21:19 +02:00
SELECT string_agg(a ORDER BY a, ',') FROM table; -- incorrect
2010-08-04 17:27:57 +02:00
</programlisting>
2010-08-05 20:21:19 +02:00
The latter is syntactically valid, but it represents a call of a
single-argument aggregate function with two <literal>ORDER BY</> keys
(the second one being rather useless since it's a constant).
2010-08-04 17:27:57 +02:00
</para>
2009-12-15 18:57:48 +01:00
<para>
If <literal>DISTINCT</> is specified in addition to an
<replaceable>order_by_clause</>, then all the <literal>ORDER BY</>
expressions must match regular arguments of the aggregate; that is,
you cannot sort on an expression that is not included in the
<literal>DISTINCT</> list.
</para>
<note>
<para>
The ability to specify both <literal>DISTINCT</> and <literal>ORDER BY</>
in an aggregate function is a <productname>PostgreSQL</> extension.
</para>
</note>
2001-01-21 23:02:01 +01:00
<para>
The predefined aggregate functions are described in <xref
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
linkend="functions-aggregate">. Other aggregate functions can be added
2008-03-20 22:42:48 +01:00
by the user.
2001-01-21 23:02:01 +01:00
</para>
2003-06-06 17:04:03 +02:00
<para>
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
An aggregate expression can only appear in the result list or
2003-06-06 17:04:03 +02:00
<literal>HAVING</> clause of a <command>SELECT</> command.
It is forbidden in other clauses, such as <literal>WHERE</>,
because those clauses are logically evaluated before the results
of aggregates are formed.
</para>
<para>
When an aggregate expression appears in a subquery (see
<xref linkend="sql-syntax-scalar-subqueries"> and
<xref linkend="functions-subquery">), the aggregate is normally
evaluated over the rows of the subquery. But an exception occurs
2006-07-27 21:52:07 +02:00
if the aggregate's arguments contain only outer-level variables:
2003-06-06 17:04:03 +02:00
the aggregate then belongs to the nearest such outer level, and is
evaluated over the rows of that query. The aggregate expression
as a whole is then an outer reference for the subquery it appears in,
and acts as a constant over any one evaluation of that subquery.
The restriction about
appearing only in the result list or <literal>HAVING</> clause
applies with respect to the query level that the aggregate belongs to.
</para>
2001-01-21 23:02:01 +01:00
</sect2>
2002-01-10 00:38:06 +01:00
2008-12-28 19:54:01 +01:00
<sect2 id="syntax-window-functions">
<title>Window Function Calls</title>
<indexterm zone="syntax-window-functions">
<primary>window function</primary>
<secondary>invocation</secondary>
</indexterm>
<indexterm zone="syntax-window-functions">
<primary>OVER clause</primary>
</indexterm>
<para>
A <firstterm>window function call</firstterm> represents the application
of an aggregate-like function over some portion of the rows selected
by a query. Unlike regular aggregate function calls, this is not tied
to grouping of the selected rows into a single output row — each
row remains separate in the query output. However the window function
is able to scan all the rows that would be part of the current row's
group according to the grouping specification (<literal>PARTITION BY</>
list) of the window function call.
The syntax of a window function call is one of the following:
<synopsis>
<replaceable>function_name</replaceable> (<optional><replaceable>expression</replaceable> <optional>, <replaceable>expression</replaceable> ... </optional></optional>) OVER ( <replaceable class="parameter">window_definition</replaceable> )
<replaceable>function_name</replaceable> (<optional><replaceable>expression</replaceable> <optional>, <replaceable>expression</replaceable> ... </optional></optional>) OVER <replaceable>window_name</replaceable>
<replaceable>function_name</replaceable> ( * ) OVER ( <replaceable class="parameter">window_definition</replaceable> )
<replaceable>function_name</replaceable> ( * ) OVER <replaceable>window_name</replaceable>
</synopsis>
where <replaceable class="parameter">window_definition</replaceable>
has the syntax
<synopsis>
2009-01-01 00:42:56 +01:00
[ <replaceable class="parameter">existing_window_name</replaceable> ]
2008-12-28 19:54:01 +01:00
[ PARTITION BY <replaceable class="parameter">expression</replaceable> [, ...] ]
[ ORDER BY <replaceable class="parameter">expression</replaceable> [ ASC | DESC | USING <replaceable class="parameter">operator</replaceable> ] [ NULLS { FIRST | LAST } ] [, ...] ]
2009-01-01 00:42:56 +01:00
[ <replaceable class="parameter">frame_clause</replaceable> ]
2008-12-31 01:08:39 +01:00
</synopsis>
2009-01-01 00:42:56 +01:00
and the optional <replaceable class="parameter">frame_clause</replaceable>
2008-12-31 01:08:39 +01:00
can be one of
<synopsis>
2010-02-12 18:33:21 +01:00
[ RANGE | ROWS ] <replaceable>frame_start</>
[ RANGE | ROWS ] BETWEEN <replaceable>frame_start</> AND <replaceable>frame_end</>
2008-12-28 19:54:01 +01:00
</synopsis>
2010-02-12 18:33:21 +01:00
where <replaceable>frame_start</> and <replaceable>frame_end</> can be
one of
<synopsis>
UNBOUNDED PRECEDING
<replaceable>value</replaceable> PRECEDING
CURRENT ROW
<replaceable>value</replaceable> FOLLOWING
UNBOUNDED FOLLOWING
</synopsis>
</para>
2008-12-28 19:54:01 +01:00
2010-02-12 18:33:21 +01:00
<para>
2008-12-28 19:54:01 +01:00
Here, <replaceable>expression</replaceable> represents any value
expression that does not itself contain window function calls.
The <literal>PARTITION BY</> and <literal>ORDER BY</> lists have
essentially the same syntax and semantics as <literal>GROUP BY</>
2009-08-27 22:08:03 +02:00
and <literal>ORDER BY</> clauses of the whole query, except that their
expressions are always just expressions and cannot be output-column
names or numbers.
2008-12-28 19:54:01 +01:00
<replaceable>window_name</replaceable> is a reference to a named window
specification defined in the query's <literal>WINDOW</literal> clause.
Named window specifications are usually referenced with just
<literal>OVER</> <replaceable>window_name</replaceable>, but it is
also possible to write a window name inside the parentheses and then
2009-01-01 00:42:56 +01:00
optionally supply an ordering clause and/or frame clause (the referenced
window must lack these clauses, if they are supplied here).
2008-12-28 19:54:01 +01:00
This latter syntax follows the same rules as modifying an existing
window name within the <literal>WINDOW</literal> clause; see the
2010-04-03 09:23:02 +02:00
<xref linkend="sql-select"> reference
2008-12-28 19:54:01 +01:00
page for details.
</para>
2008-12-31 01:08:39 +01:00
<para>
2009-01-01 00:42:56 +01:00
The <replaceable class="parameter">frame_clause</replaceable> specifies
the set of rows constituting the <firstterm>window frame</>, for those
window functions that act on the frame instead of the whole partition.
2010-02-12 18:33:21 +01:00
If <replaceable>frame_end</> is omitted it defaults to <literal>CURRENT
ROW</>. Restrictions are that
<replaceable>frame_start</> cannot be <literal>UNBOUNDED FOLLOWING</>,
<replaceable>frame_end</> cannot be <literal>UNBOUNDED PRECEDING</>,
and the <replaceable>frame_end</> choice cannot appear earlier in the
above list than the <replaceable>frame_start</> choice — for example
<literal>RANGE BETWEEN CURRENT ROW AND <replaceable>value</>
PRECEDING</literal> is not allowed.
2008-12-31 01:08:39 +01:00
The default framing option is <literal>RANGE UNBOUNDED PRECEDING</>,
which is the same as <literal>RANGE BETWEEN UNBOUNDED PRECEDING AND
2010-02-12 18:33:21 +01:00
CURRENT ROW</>; it sets the frame to be all rows from the partition start
up through the current row's last peer in the <literal>ORDER BY</>
ordering (which means all rows if there is no <literal>ORDER BY</>).
In general, <literal>UNBOUNDED PRECEDING</> means that the frame
starts with the first row of the partition, and similarly
<literal>UNBOUNDED FOLLOWING</> means that the frame ends with the last
row of the partition (regardless of <literal>RANGE</> or <literal>ROWS</>
mode). In <literal>ROWS</> mode, <literal>CURRENT ROW</>
means that the frame starts or ends with the current row; but in
<literal>RANGE</> mode it means that the frame starts or ends with
the current row's first or last peer in the <literal>ORDER BY</> ordering.
The <replaceable>value</> <literal>PRECEDING</> and
<replaceable>value</> <literal>FOLLOWING</> cases are currently only
allowed in <literal>ROWS</> mode. They indicate that the frame starts
or ends with the row that many rows before or after the current row.
<replaceable>value</replaceable> must be an integer expression not
containing any variables, aggregate functions, or window functions.
The value must not be null or negative; but it can be zero, which
selects the current row itself.
2008-12-31 01:08:39 +01:00
</para>
2008-12-28 19:54:01 +01:00
<para>
The built-in window functions are described in <xref
2009-01-01 00:42:56 +01:00
linkend="functions-window-table">. Other window functions can be added by
the user. Also, any built-in or user-defined aggregate function can be
used as a window function.
2008-12-28 19:54:01 +01:00
</para>
<para>
The syntaxes using <literal>*</> are used for calling parameter-less
aggregate functions as window functions, for example
<literal>count(*) OVER (PARTITION BY x ORDER BY y)</>.
<literal>*</> is customarily not used for non-aggregate window functions.
Aggregate window functions, unlike normal aggregate functions, do not
2009-12-15 18:57:48 +01:00
allow <literal>DISTINCT</> or <literal>ORDER BY</> to be used within the
function argument list.
2008-12-28 19:54:01 +01:00
</para>
<para>
Window function calls are permitted only in the <literal>SELECT</literal>
list and the <literal>ORDER BY</> clause of the query.
</para>
<para>
More information about window functions can be found in
2010-07-03 04:57:46 +02:00
<xref linkend="tutorial-window">,
<xref linkend="functions-window">,
2008-12-28 19:54:01 +01:00
<xref linkend="queries-window">.
</para>
</sect2>
2002-01-10 00:38:06 +01:00
<sect2 id="sql-syntax-type-casts">
<title>Type Casts</title>
2003-08-31 19:32:24 +02:00
<indexterm>
<primary>data type</primary>
<secondary>type cast</secondary>
</indexterm>
<indexterm>
<primary>type cast</primary>
</indexterm>
2002-01-10 00:38:06 +01:00
2010-06-09 18:43:47 +02:00
<indexterm>
<primary>::</primary>
</indexterm>
2002-01-10 00:38:06 +01:00
<para>
2002-01-20 23:19:57 +01:00
A type cast specifies a conversion from one data type to another.
2002-01-10 00:38:06 +01:00
<productname>PostgreSQL</productname> accepts two equivalent syntaxes
for type casts:
<synopsis>
CAST ( <replaceable>expression</replaceable> AS <replaceable>type</replaceable> )
<replaceable>expression</replaceable>::<replaceable>type</replaceable>
</synopsis>
2002-11-11 21:14:04 +01:00
The <literal>CAST</> syntax conforms to SQL; the syntax with
2002-01-10 00:38:06 +01:00
<literal>::</literal> is historical <productname>PostgreSQL</productname>
usage.
</para>
<para>
When a cast is applied to a value expression of a known type, it
represents a run-time type conversion. The cast will succeed only
2004-06-16 03:27:00 +02:00
if a suitable type conversion operation has been defined. Notice that this
2002-01-10 00:38:06 +01:00
is subtly different from the use of casts with constants, as shown in
<xref linkend="sql-syntax-constants-generic">. A cast applied to an
unadorned string literal represents the initial assignment of a type
to a literal constant value, and so it will succeed for any type
2002-01-20 23:19:57 +01:00
(if the contents of the string literal are acceptable input syntax for the
data type).
2002-01-10 00:38:06 +01:00
</para>
<para>
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
An explicit type cast can usually be omitted if there is no ambiguity as
2002-04-25 22:14:43 +02:00
to the type that a value expression must produce (for example, when it is
2002-01-10 00:38:06 +01:00
assigned to a table column); the system will automatically apply a
2002-04-25 22:14:43 +02:00
type cast in such cases. However, automatic casting is only done for
2002-11-11 21:14:04 +01:00
casts that are marked <quote>OK to apply implicitly</>
in the system catalogs. Other casts must be invoked with
2002-04-25 22:14:43 +02:00
explicit casting syntax. This restriction is intended to prevent
2009-06-17 23:58:49 +02:00
surprising conversions from being applied silently.
2002-01-10 00:38:06 +01:00
</para>
<para>
It is also possible to specify a type cast using a function-like
syntax:
<synopsis>
<replaceable>typename</replaceable> ( <replaceable>expression</replaceable> )
</synopsis>
However, this only works for types whose names are also valid as
function names. For example, <literal>double precision</literal>
Wording cleanup for error messages. Also change can't -> cannot.
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
2007-02-01 20:10:30 +01:00
cannot be used this way, but the equivalent <literal>float8</literal>
2002-01-10 00:38:06 +01:00
can. Also, the names <literal>interval</>, <literal>time</>, and
<literal>timestamp</> can only be used in this fashion if they are
2002-04-25 22:14:43 +02:00
double-quoted, because of syntactic conflicts. Therefore, the use of
2002-01-10 00:38:06 +01:00
the function-like cast syntax leads to inconsistencies and should
2009-04-27 18:27:36 +02:00
probably be avoided.
2002-01-10 00:38:06 +01:00
</para>
2007-06-05 23:31:09 +02:00
<note>
<para>
The function-like syntax is in fact just a function call. When
one of the two standard cast syntaxes is used to do a run-time
conversion, it will internally invoke a registered function to
perform the conversion. By convention, these conversion functions
have the same name as their output type, and thus the <quote>function-like
syntax</> is nothing more than a direct invocation of the underlying
conversion function. Obviously, this is not something that a portable
application should rely on. For further details see
2010-04-03 09:23:02 +02:00
<xref linkend="sql-createcast">.
2007-06-05 23:31:09 +02:00
</para>
</note>
2002-01-10 00:38:06 +01:00
</sect2>
2011-03-09 04:50:15 +01:00
<sect2 id="sql-syntax-collate-exprs">
<title>Collation Expressions</title>
2011-02-08 22:04:18 +01:00
<indexterm>
<primary>COLLATE</primary>
</indexterm>
<para>
The <literal>COLLATE</literal> clause overrides the collation of
an expression. It is appended to the expression it applies to:
<synopsis>
<replaceable>expr</replaceable> COLLATE <replaceable>collation</replaceable>
</synopsis>
where <replaceable>collation</replaceable> is a possibly
schema-qualified identifier. The <literal>COLLATE</literal>
clause binds tighter than operators; parentheses can be used when
necessary.
</para>
<para>
If no collation is explicitly specified, the database system
either derives a collation from the columns involved in the
expression, or it defaults to the default collation of the
database if no column is involved in the expression.
</para>
<para>
2011-03-09 04:50:15 +01:00
The two common uses of the <literal>COLLATE</literal> clause are
2011-02-08 22:04:18 +01:00
overriding the sort order in an <literal>ORDER BY</> clause, for
example:
<programlisting>
SELECT a, b, c FROM tbl WHERE ... ORDER BY a COLLATE "C";
</programlisting>
and overriding the collation of a function or operator call that
has locale-sensitive results, for example:
<programlisting>
2011-03-09 04:50:15 +01:00
SELECT * FROM tbl WHERE a > 'foo' COLLATE "C";
</programlisting>
Note that in the latter case the <literal>COLLATE</> clause is
attached to an input argument of the operator we wish to affect.
It doesn't matter which argument of the operator or function call the
<literal>COLLATE</> clause is attached to, because the collation that is
applied by the operator or function is derived by considering all
arguments, and an explicit <literal>COLLATE</> clause will override the
collations of all other arguments. (Attaching non-matching
<literal>COLLATE</> clauses to more than one argument, however, is an
error. For more details see <xref linkend="collation">.)
Thus, this gives the same result as the previous example:
<programlisting>
SELECT * FROM tbl WHERE a COLLATE "C" > 'foo';
</programlisting>
But this is an error:
<programlisting>
SELECT * FROM tbl WHERE (a > 'foo') COLLATE "C";
2011-02-08 22:04:18 +01:00
</programlisting>
2011-03-09 04:50:15 +01:00
because it attempts to apply a collation to the result of the
<literal>></> operator, which is of the non-collatable data type
<type>boolean</>.
2011-02-08 22:04:18 +01:00
</para>
</sect2>
2003-06-06 17:04:03 +02:00
<sect2 id="sql-syntax-scalar-subqueries">
2002-01-10 00:38:06 +01:00
<title>Scalar Subqueries</title>
2003-08-31 19:32:24 +02:00
<indexterm>
<primary>subquery</primary>
</indexterm>
2002-01-10 00:38:06 +01:00
<para>
A scalar subquery is an ordinary
2002-11-11 21:14:04 +01:00
<command>SELECT</command> query in parentheses that returns exactly one
row with one column. (See <xref linkend="queries"> for information about writing queries.)
The <command>SELECT</command> query is executed
2002-01-10 00:38:06 +01:00
and the single returned value is used in the surrounding value expression.
It is an error to use a query that
returns more than one row or more than one column as a scalar subquery.
(But if, during a particular execution, the subquery returns no rows,
2002-09-21 20:32:54 +02:00
there is no error; the scalar result is taken to be null.)
2002-01-10 00:38:06 +01:00
The subquery can refer to variables from the surrounding query,
which will act as constants during any one evaluation of the subquery.
2003-11-04 10:55:39 +01:00
See also <xref linkend="functions-subquery"> for other expressions involving subqueries.
2002-01-10 00:38:06 +01:00
</para>
<para>
For example, the following finds the largest city population in each
state:
<programlisting>
SELECT name, (SELECT max(pop) FROM cities WHERE cities.state = states.name)
2002-11-11 21:14:04 +01:00
FROM states;
2002-01-10 00:38:06 +01:00
</programlisting>
</para>
</sect2>
1999-07-22 17:11:05 +02:00
2003-08-10 00:50:22 +02:00
<sect2 id="sql-syntax-array-constructors">
<title>Array Constructors</title>
2003-08-31 19:32:24 +02:00
<indexterm>
<primary>array</primary>
<secondary>constructor</secondary>
</indexterm>
2003-08-10 00:50:22 +02:00
2004-10-27 00:16:12 +02:00
<indexterm>
<primary>ARRAY</primary>
</indexterm>
2003-08-10 00:50:22 +02:00
<para>
2003-11-04 10:55:39 +01:00
An array constructor is an expression that builds an
2009-06-17 23:58:49 +02:00
array value using values for its member elements. A simple array
2008-03-20 22:42:48 +01:00
constructor
2003-11-01 02:56:29 +01:00
consists of the key word <literal>ARRAY</literal>, a left square bracket
2008-03-20 22:42:48 +01:00
<literal>[</>, a list of expressions (separated by commas) for the
2003-08-10 00:50:22 +02:00
array element values, and finally a right square bracket <literal>]</>.
2007-02-01 01:28:19 +01:00
For example:
2003-08-10 00:50:22 +02:00
<programlisting>
SELECT ARRAY[1,2,3+4];
array
---------
{1,2,7}
(1 row)
</programlisting>
2008-03-20 22:42:48 +01:00
By default,
the array element type is the common type of the member expressions,
2003-08-10 00:50:22 +02:00
determined using the same rules as for <literal>UNION</> or
2008-03-20 22:42:48 +01:00
<literal>CASE</> constructs (see <xref linkend="typeconv-union-case">).
You can override this by explicitly casting the array constructor to the
desired type, for example:
<programlisting>
SELECT ARRAY[1,2,22.7]::integer[];
array
----------
{1,2,23}
(1 row)
</programlisting>
This has the same effect as casting each expression to the array
element type individually.
For more on casting, see <xref linkend="sql-syntax-type-casts">.
2003-08-10 00:50:22 +02:00
</para>
<para>
Multidimensional array values can be built by nesting array
constructors.
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
In the inner constructors, the key word <literal>ARRAY</literal> can
2003-08-10 00:50:22 +02:00
be omitted. For example, these produce the same result:
<programlisting>
SELECT ARRAY[ARRAY[1,2], ARRAY[3,4]];
array
---------------
{{1,2},{3,4}}
(1 row)
SELECT ARRAY[[1,2],[3,4]];
array
---------------
{{1,2},{3,4}}
(1 row)
</programlisting>
Since multidimensional arrays must be rectangular, inner constructors
at the same level must produce sub-arrays of identical dimensions.
2008-03-20 22:42:48 +01:00
Any cast applied to the outer <literal>ARRAY</> constructor propagates
automatically to all the inner constructors.
2003-08-10 00:50:22 +02:00
</para>
2003-08-19 08:06:48 +02:00
<para>
Multidimensional array constructor elements can be anything yielding
an array of the proper kind, not only a sub-<literal>ARRAY</> construct.
For example:
<programlisting>
2003-11-04 10:55:39 +01:00
CREATE TABLE arr(f1 int[], f2 int[]);
INSERT INTO arr VALUES (ARRAY[[1,2],[3,4]], ARRAY[[5,6],[7,8]]);
SELECT ARRAY[f1, f2, '{{9,10},{11,12}}'::int[]] FROM arr;
2003-08-19 08:06:48 +02:00
array
------------------------------------------------
{{{1,2},{3,4}},{{5,6},{7,8}},{{9,10},{11,12}}}
(1 row)
</programlisting>
</para>
2008-03-20 22:42:48 +01:00
<para>
You can construct an empty array, but since it's impossible to have an
array with no type, you must explicitly cast your empty array to the
desired type. For example:
<programlisting>
SELECT ARRAY[]::integer[];
array
-------
{}
(1 row)
</programlisting>
</para>
2003-08-10 00:50:22 +02:00
<para>
It is also possible to construct an array from the results of a
subquery. In this form, the array constructor is written with the
2003-11-01 02:56:29 +01:00
key word <literal>ARRAY</literal> followed by a parenthesized (not
2003-08-10 00:50:22 +02:00
bracketed) subquery. For example:
<programlisting>
SELECT ARRAY(SELECT oid FROM pg_proc WHERE proname LIKE 'bytea%');
?column?
-------------------------------------------------------------
{2011,1954,1948,1952,1951,1244,1950,2005,1949,1953,2006,31}
(1 row)
</programlisting>
2003-11-04 10:55:39 +01:00
The subquery must return a single column. The resulting
one-dimensional array will have an element for each row in the
subquery result, with an element type matching that of the
subquery's output column.
2003-08-10 00:50:22 +02:00
</para>
<para>
The subscripts of an array value built with <literal>ARRAY</literal>
always begin with one. For more information about arrays, see
<xref linkend="arrays">.
</para>
</sect2>
2004-05-11 00:44:49 +02:00
<sect2 id="sql-syntax-row-constructors">
<title>Row Constructors</title>
<indexterm>
2004-06-07 06:04:47 +02:00
<primary>composite type</primary>
<secondary>constructor</secondary>
</indexterm>
<indexterm>
<primary>row type</primary>
2004-05-11 00:44:49 +02:00
<secondary>constructor</secondary>
</indexterm>
2004-10-27 00:16:12 +02:00
<indexterm>
<primary>ROW</primary>
</indexterm>
2004-05-11 00:44:49 +02:00
<para>
2009-06-17 23:58:49 +02:00
A row constructor is an expression that builds a row value (also
2009-04-27 18:27:36 +02:00
called a composite value) using values
2004-05-11 00:44:49 +02:00
for its member fields. A row constructor consists of the key word
2004-10-27 00:16:12 +02:00
<literal>ROW</literal>, a left parenthesis, zero or more
2004-05-11 00:44:49 +02:00
expressions (separated by commas) for the row field values, and finally
2007-02-01 01:28:19 +01:00
a right parenthesis. For example:
2004-05-11 00:44:49 +02:00
<programlisting>
2004-06-07 06:04:47 +02:00
SELECT ROW(1,2.5,'this is a test');
2004-05-11 00:44:49 +02:00
</programlisting>
The key word <literal>ROW</> is optional when there is more than one
expression in the list.
</para>
2006-06-26 19:24:41 +02:00
<para>
A row constructor can include the syntax
<replaceable>rowvalue</replaceable><literal>.*</literal>,
which will be expanded to a list of the elements of the row value,
just as occurs when the <literal>.*</> syntax is used at the top level
of a <command>SELECT</> list. For example, if table <literal>t</> has
columns <literal>f1</> and <literal>f2</>, these are the same:
<programlisting>
SELECT ROW(t.*, 42) FROM t;
SELECT ROW(t.f1, t.f2, 42) FROM t;
</programlisting>
</para>
<note>
<para>
Before <productname>PostgreSQL</productname> 8.2, the
<literal>.*</literal> syntax was not expanded, so that writing
<literal>ROW(t.*, 42)</> created a two-field row whose first field
was another row value. The new behavior is usually more useful.
If you need the old behavior of nested row values, write the inner
row value without <literal>.*</literal>, for instance
<literal>ROW(t, 42)</>.
</para>
</note>
2004-05-11 00:44:49 +02:00
<para>
By default, the value created by a <literal>ROW</> expression is of
an anonymous record type. If necessary, it can be cast to a named
2004-12-13 19:05:10 +01:00
composite type — either the row type of a table, or a composite type
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
created with <command>CREATE TYPE AS</>. An explicit cast might be needed
2004-05-11 00:44:49 +02:00
to avoid ambiguity. For example:
<programlisting>
CREATE TABLE mytable(f1 int, f2 float, f3 text);
2004-12-23 06:37:40 +01:00
2004-05-11 00:44:49 +02:00
CREATE FUNCTION getf1(mytable) RETURNS int AS 'SELECT $1.f1' LANGUAGE SQL;
2004-12-23 06:37:40 +01:00
2004-05-11 00:44:49 +02:00
-- No cast needed since only one getf1() exists
SELECT getf1(ROW(1,2.5,'this is a test'));
getf1
-------
1
(1 row)
CREATE TYPE myrowtype AS (f1 int, f2 text, f3 numeric);
2004-12-23 06:37:40 +01:00
2004-05-11 00:44:49 +02:00
CREATE FUNCTION getf1(myrowtype) RETURNS int AS 'SELECT $1.f1' LANGUAGE SQL;
2004-12-23 06:37:40 +01:00
2004-05-11 00:44:49 +02:00
-- Now we need a cast to indicate which function to call:
SELECT getf1(ROW(1,2.5,'this is a test'));
ERROR: function getf1(record) is not unique
2004-12-23 06:37:40 +01:00
2004-05-11 00:44:49 +02:00
SELECT getf1(ROW(1,2.5,'this is a test')::mytable);
getf1
-------
1
(1 row)
SELECT getf1(CAST(ROW(11,'this is a test',2.5) AS myrowtype));
getf1
-------
11
(1 row)
</programlisting>
</para>
<para>
2004-06-07 06:04:47 +02:00
Row constructors can be used to build composite values to be stored
in a composite-type table column, or to be passed to a function that
accepts a composite parameter. Also,
it is possible to compare two row values or test a row with
2007-02-01 01:28:19 +01:00
<literal>IS NULL</> or <literal>IS NOT NULL</>, for example:
2004-05-11 00:44:49 +02:00
<programlisting>
SELECT ROW(1,2.5,'this is a test') = ROW(1, 3, 'not the same');
2004-12-23 06:37:40 +01:00
2006-06-26 19:24:41 +02:00
SELECT ROW(table.*) IS NULL FROM table; -- detect all-null rows
2004-05-11 00:44:49 +02:00
</programlisting>
For more detail see <xref linkend="functions-comparisons">.
Row constructors can also be used in connection with subqueries,
as discussed in <xref linkend="functions-subquery">.
</para>
</sect2>
2003-08-04 16:00:14 +02:00
<sect2 id="syntax-express-eval">
2003-08-10 00:50:22 +02:00
<title>Expression Evaluation Rules</title>
2000-12-14 23:30:56 +01:00
2003-08-31 19:32:24 +02:00
<indexterm>
<primary>expression</primary>
<secondary>order of evaluation</secondary>
</indexterm>
2002-06-01 22:56:55 +02:00
<para>
The order of evaluation of subexpressions is not defined. In
2002-06-15 23:28:55 +02:00
particular, the inputs of an operator or function are not necessarily
evaluated left-to-right or in any other fixed order.
2002-06-01 22:56:55 +02:00
</para>
2001-05-13 00:51:36 +02:00
2000-12-14 23:30:56 +01:00
<para>
2002-06-01 22:56:55 +02:00
Furthermore, if the result of an expression can be determined by
2002-06-15 23:28:55 +02:00
evaluating only some parts of it, then other subexpressions
2007-02-01 01:28:19 +01:00
might not be evaluated at all. For instance, if one wrote:
2000-12-14 23:30:56 +01:00
<programlisting>
2002-06-01 22:56:55 +02:00
SELECT true OR somefunc();
2000-12-14 23:30:56 +01:00
</programlisting>
2002-06-01 22:56:55 +02:00
then <literal>somefunc()</literal> would (probably) not be called
2007-02-01 01:28:19 +01:00
at all. The same would be the case if one wrote:
2000-12-14 23:30:56 +01:00
<programlisting>
2002-06-01 22:56:55 +02:00
SELECT somefunc() OR true;
2001-02-10 08:08:44 +01:00
</programlisting>
2002-06-01 22:56:55 +02:00
Note that this is not the same as the left-to-right
<quote>short-circuiting</quote> of Boolean operators that is found
in some programming languages.
2000-12-14 23:30:56 +01:00
</para>
<para>
2002-06-01 22:56:55 +02:00
As a consequence, it is unwise to use functions with side effects
2002-06-15 23:28:55 +02:00
as part of complex expressions. It is particularly dangerous to
2002-11-11 21:14:04 +01:00
rely on side effects or evaluation order in <literal>WHERE</> and <literal>HAVING</> clauses,
2002-06-15 23:28:55 +02:00
since those clauses are extensively reprocessed as part of
developing an execution plan. Boolean
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
expressions (<literal>AND</>/<literal>OR</>/<literal>NOT</> combinations) in those clauses can be reorganized
2002-06-15 23:28:55 +02:00
in any manner allowed by the laws of Boolean algebra.
</para>
<para>
2002-11-11 21:14:04 +01:00
When it is essential to force evaluation order, a <literal>CASE</>
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
construct (see <xref linkend="functions-conditional">) can be
2002-11-11 21:14:04 +01:00
used. For example, this is an untrustworthy way of trying to
avoid division by zero in a <literal>WHERE</> clause:
2002-06-15 23:28:55 +02:00
<programlisting>
2008-01-23 20:51:29 +01:00
SELECT ... WHERE x > 0 AND y/x > 1.5;
2002-06-15 23:28:55 +02:00
</programlisting>
2002-11-11 21:14:04 +01:00
But this is safe:
2002-06-15 23:28:55 +02:00
<programlisting>
2008-01-23 20:51:29 +01:00
SELECT ... WHERE CASE WHEN x > 0 THEN y/x > 1.5 ELSE false END;
2002-06-15 23:28:55 +02:00
</programlisting>
2003-08-15 01:13:27 +02:00
A <literal>CASE</> construct used in this fashion will defeat optimization
attempts, so it should only be done when necessary. (In this particular
2008-01-23 20:51:29 +01:00
example, it would be better to sidestep the problem by writing
2003-08-15 01:13:27 +02:00
<literal>y > 1.5*x</> instead.)
2000-12-14 23:30:56 +01:00
</para>
2002-06-01 22:56:55 +02:00
</sect2>
</sect1>
2001-01-21 23:02:01 +01:00
2009-10-08 04:39:25 +02:00
<sect1 id="sql-syntax-calling-funcs">
<title>Calling Functions</title>
<indexterm zone="sql-syntax-calling-funcs">
<primary>notation</primary>
<secondary>functions</secondary>
</indexterm>
<para>
<productname>PostgreSQL</productname> allows functions that have named
parameters to be called using either <firstterm>positional</firstterm> or
<firstterm>named</firstterm> notation. Named notation is especially
useful for functions that have a large number of parameters, since it
makes the associations between parameters and actual arguments more
explicit and reliable.
In positional notation, a function call is written with
its argument values in the same order as they are defined in the function
declaration. In named notation, the arguments are matched to the
function parameters by name and can be written in any order.
</para>
<para>
In either notation, parameters that have default values given in the
function declaration need not be written in the call at all. But this
is particularly useful in named notation, since any combination of
parameters can be omitted; while in positional notation parameters can
only be omitted from right to left.
</para>
<para>
<productname>PostgreSQL</productname> also supports
<firstterm>mixed</firstterm> notation, which combines positional and
named notation. In this case, positional parameters are written first
and named parameters appear after them.
</para>
<para>
The following examples will illustrate the usage of all three
notations, using the following function definition:
<programlisting>
CREATE FUNCTION concat_lower_or_upper(a text, b text, uppercase boolean DEFAULT false)
RETURNS text
AS
$$
SELECT CASE
WHEN $3 THEN UPPER($1 || ' ' || $2)
ELSE LOWER($1 || ' ' || $2)
END;
$$
LANGUAGE SQL IMMUTABLE STRICT;
</programlisting>
Function <function>concat_lower_or_upper</function> has two mandatory
parameters, <literal>a</literal> and <literal>b</literal>. Additionally
there is one optional parameter <literal>uppercase</literal> which defaults
to <literal>false</literal>. The <literal>a</literal> and
<literal>b</literal> inputs will be concatenated, and forced to either
upper or lower case depending on the <literal>uppercase</literal>
parameter. The remaining details of this function
definition are not important here (see <xref linkend="extend"> for
more information).
</para>
<sect2 id="sql-syntax-calling-funcs-positional">
2011-01-29 19:00:18 +01:00
<title>Using Positional Notation</title>
2009-10-08 04:39:25 +02:00
<indexterm>
<primary>function</primary>
<secondary>positional notation</secondary>
</indexterm>
<para>
Positional notation is the traditional mechanism for passing arguments
to functions in <productname>PostgreSQL</productname>. An example is:
<screen>
SELECT concat_lower_or_upper('Hello', 'World', true);
concat_lower_or_upper
-----------------------
HELLO WORLD
(1 row)
</screen>
All arguments are specified in order. The result is upper case since
<literal>uppercase</literal> is specified as <literal>true</literal>.
Another example is:
<screen>
SELECT concat_lower_or_upper('Hello', 'World');
concat_lower_or_upper
-----------------------
hello world
(1 row)
</screen>
Here, the <literal>uppercase</literal> parameter is omitted, so it
receives its default value of <literal>false</literal>, resulting in
lower case output. In positional notation, arguments can be omitted
from right to left so long as they have defaults.
</para>
</sect2>
<sect2 id="sql-syntax-calling-funcs-named">
2011-01-29 19:00:18 +01:00
<title>Using Named Notation</title>
2009-10-08 04:39:25 +02:00
<indexterm>
<primary>function</primary>
<secondary>named notation</secondary>
</indexterm>
<para>
2010-05-30 20:10:41 +02:00
In named notation, each argument's name is specified using
<literal>:=</literal> to separate it from the argument expression.
For example:
2009-10-08 04:39:25 +02:00
<screen>
2010-05-30 20:10:41 +02:00
SELECT concat_lower_or_upper(a := 'Hello', b := 'World');
2009-10-08 04:39:25 +02:00
concat_lower_or_upper
-----------------------
hello world
(1 row)
</screen>
Again, the argument <literal>uppercase</literal> was omitted
so it is set to <literal>false</literal> implicitly. One advantage of
using named notation is that the arguments may be specified in any
order, for example:
<screen>
2010-05-30 20:10:41 +02:00
SELECT concat_lower_or_upper(a := 'Hello', b := 'World', uppercase := true);
2009-10-08 04:39:25 +02:00
concat_lower_or_upper
-----------------------
HELLO WORLD
(1 row)
2010-05-30 20:10:41 +02:00
SELECT concat_lower_or_upper(a := 'Hello', uppercase := true, b := 'World');
2009-10-08 04:39:25 +02:00
concat_lower_or_upper
-----------------------
HELLO WORLD
(1 row)
</screen>
</para>
</sect2>
<sect2 id="sql-syntax-calling-funcs-mixed">
2011-01-29 19:00:18 +01:00
<title>Using Mixed Notation</title>
2009-10-08 04:39:25 +02:00
<indexterm>
<primary>function</primary>
<secondary>mixed notation</secondary>
</indexterm>
<para>
The mixed notation combines positional and named notation. However, as
already mentioned, named arguments cannot precede positional arguments.
For example:
<screen>
2010-05-30 20:10:41 +02:00
SELECT concat_lower_or_upper('Hello', 'World', uppercase := true);
2009-10-08 04:39:25 +02:00
concat_lower_or_upper
-----------------------
HELLO WORLD
(1 row)
</screen>
In the above query, the arguments <literal>a</literal> and
<literal>b</literal> are specified positionally, while
<literal>uppercase</> is specified by name. In this example,
that adds little except documentation. With a more complex function
having numerous parameters that have default values, named or mixed
notation can save a great deal of writing and reduce chances for error.
</para>
</sect2>
</sect1>
2001-01-21 23:02:01 +01:00
</chapter>