OSDN Git Service

Random copy-editing.
[pg-rex/syncrep.git] / doc / src / sgml / syntax.sgml
1 <!--
2 $Header: /cvsroot/pgsql/doc/src/sgml/syntax.sgml,v 1.86 2003/11/04 09:55:39 petere Exp $
3 -->
4
5 <chapter id="sql-syntax">
6  <title>SQL Syntax</title>
7
8  <indexterm zone="sql-syntax">
9   <primary>syntax</primary>
10   <secondary>SQL</secondary>
11  </indexterm>
12
13  <para>
14   This chapter describes the syntax of SQL.  It forms the foundation
15   for understanding the following chapters which will go into detail
16   about how the SQL commands are applied to define and modify data.
17  </para>
18
19  <para>
20   We also advise users who are already familiar with SQL to read this
21   chapter carefully because there are several rules and concepts that
22   are implemented inconsistently among SQL databases or that are
23   specific to <productname>PostgreSQL</productname>.
24  </para>
25
26  <sect1 id="sql-syntax-lexical">
27   <title>Lexical Structure</title>
28
29   <indexterm>
30    <primary>token</primary>
31   </indexterm>
32
33   <para>
34    SQL input consists of a sequence of
35    <firstterm>commands</firstterm>.  A command is composed of a
36    sequence of <firstterm>tokens</firstterm>, terminated by a
37    semicolon (<quote>;</quote>).  The end of the input stream also
38    terminates a command.  Which tokens are valid depends on the syntax
39    of the particular command.
40   </para>
41
42   <para>
43    A token can be a <firstterm>key word</firstterm>, an
44    <firstterm>identifier</firstterm>, a <firstterm>quoted
45    identifier</firstterm>, a <firstterm>literal</firstterm> (or
46    constant), or a special character symbol.  Tokens are normally
47    separated by whitespace (space, tab, newline), but need not be if
48    there is no ambiguity (which is generally only the case if a
49    special character is adjacent to some other token type).
50   </para>
51
52   <para>
53    Additionally, <firstterm>comments</firstterm> can occur in SQL
54    input.  They are not tokens, they are effectively equivalent to
55    whitespace.
56   </para>
57
58    <para>
59     For example, the following is (syntactically) valid SQL input:
60 <programlisting>
61 SELECT * FROM MY_TABLE;
62 UPDATE MY_TABLE SET A = 5;
63 INSERT INTO MY_TABLE VALUES (3, 'hi there');
64 </programlisting>
65     This is a sequence of three commands, one per line (although this
66     is not required; more than one command can be on a line, and
67     commands can usefully be split across lines).
68    </para>
69
70   <para>
71    The SQL syntax is not very consistent regarding what tokens
72    identify commands and which are operands or parameters.  The first
73    few tokens are generally the command name, so in the above example
74    we would usually speak of a <quote>SELECT</quote>, an
75    <quote>UPDATE</quote>, and an <quote>INSERT</quote> command.  But
76    for instance the <command>UPDATE</command> command always requires
77    a <token>SET</token> token to appear in a certain position, and
78    this particular variation of <command>INSERT</command> also
79    requires a <token>VALUES</token> in order to be complete.  The
80    precise syntax rules for each command are described in <xref linkend="reference">.
81   </para>
82
83   <sect2 id="sql-syntax-identifiers">
84    <title>Identifiers and Key Words</title>
85
86    <indexterm zone="sql-syntax-identifiers">
87     <primary>identifier</primary>
88     <secondary>syntax of</secondary>
89    </indexterm>
90
91    <indexterm zone="sql-syntax-identifiers">
92     <primary>name</primary>
93     <secondary>syntax of</secondary>
94    </indexterm>
95
96    <indexterm zone="sql-syntax-identifiers">
97     <primary>key word</primary>
98     <secondary>syntax of</secondary>
99    </indexterm>
100
101    <para>
102     Tokens such as <token>SELECT</token>, <token>UPDATE</token>, or
103     <token>VALUES</token> in the example above are examples of
104     <firstterm>key words</firstterm>, that is, words that have a fixed
105     meaning in the SQL language.  The tokens <token>MY_TABLE</token>
106     and <token>A</token> are examples of
107     <firstterm>identifiers</firstterm>.  They identify names of
108     tables, columns, or other database objects, depending on the
109     command they are used in.  Therefore they are sometimes simply
110     called <quote>names</quote>.  Key words and identifiers have the
111     same lexical structure, meaning that one cannot know whether a
112     token is an identifier or a key word without knowing the language.
113     A complete list of key words can be found in <xref
114     linkend="sql-keywords-appendix">.
115    </para>
116
117    <para>
118     SQL identifiers and key words must begin with a letter
119     (<literal>a</literal>-<literal>z</literal>, but also letters with
120     diacritical marks and non-Latin letters) or an underscore
121     (<literal>_</literal>).  Subsequent characters in an identifier or
122     key word can be letters, underscores, digits
123     (<literal>0</literal>-<literal>9</literal>), or dollar signs
124     (<literal>$</>).  Note that dollar signs are not allowed in identifiers
125     according to the letter of the SQL standard, so their use may render
126     applications less portable.
127     The SQL standard will not define a key word that contains
128     digits or starts or ends with an underscore, so identifiers of this
129     form are safe against possible conflict with future extensions of the
130     standard.
131    </para>
132
133    <para>
134     <indexterm><primary>identifier</primary><secondary>length</secondary></indexterm>
135     The system uses no more than <symbol>NAMEDATALEN</symbol>-1
136     characters of an identifier; longer names can be written in
137     commands, but they will be truncated.  By default,
138     <symbol>NAMEDATALEN</symbol> is 64 so the maximum identifier
139     length is 63. If this limit is problematic, it can be raised by
140     changing the <symbol>NAMEDATALEN</symbol> constant in
141     <filename>src/include/postgres_ext.h</filename>.
142    </para>
143
144    <para>
145     <indexterm>
146      <primary>case sensitivity</primary>
147      <secondary>of SQL commands</secondary>
148     </indexterm>
149     Identifier and key word names are case insensitive.  Therefore
150 <programlisting>
151 UPDATE MY_TABLE SET A = 5;
152 </programlisting>
153     can equivalently be written as
154 <programlisting>
155 uPDaTE my_TabLE SeT a = 5;
156 </programlisting>
157     A convention often used is to write key words in upper
158     case and names in lower case, e.g.,
159 <programlisting>
160 UPDATE my_table SET a = 5;
161 </programlisting>
162    </para>
163
164    <para>
165     <indexterm>
166      <primary>quotation marks</primary>
167      <secondary>and identifiers</secondary>
168     </indexterm>
169     There is a second kind of identifier:  the <firstterm>delimited
170     identifier</firstterm> or <firstterm>quoted
171     identifier</firstterm>.  It is formed by enclosing an arbitrary
172     sequence of characters in double-quotes
173     (<literal>"</literal>). <!-- " font-lock mania --> A delimited
174     identifier is always an identifier, never a key word.  So
175     <literal>"select"</literal> could be used to refer to a column or
176     table named <quote>select</quote>, whereas an unquoted
177     <literal>select</literal> would be taken as a key word and
178     would therefore provoke a parse error when used where a table or
179     column name is expected.  The example can be written with quoted
180     identifiers like this:
181 <programlisting>
182 UPDATE "my_table" SET "a" = 5;
183 </programlisting>
184    </para>
185
186    <para>
187     Quoted identifiers can contain any character other than a double
188     quote itself.  To include a double quote, write two double quotes.
189     This allows constructing table or column names that would
190     otherwise not be possible, such as ones containing spaces or
191     ampersands.  The length limitation still applies.
192    </para>
193
194    <para>
195     Quoting an identifier also makes it case-sensitive, whereas
196     unquoted names are always folded to lower case.  For example, the
197     identifiers <literal>FOO</literal>, <literal>foo</literal>, and
198     <literal>"foo"</literal> are considered the same by
199     <productname>PostgreSQL</productname>, but
200     <literal>"Foo"</literal> and <literal>"FOO"</literal> are
201     different from these three and each other.  (The folding of
202     unquoted names to lower case in <productname>PostgreSQL</> is
203     incompatible with the SQL standard, which says that unquoted names
204     should be folded to upper case.  Thus, <literal>foo</literal>
205     should be equivalent to <literal>"FOO"</literal> not
206     <literal>"foo"</literal> according to the standard.  If you want
207     to write portable applications you are advised to always quote a
208     particular name or never quote it.
209    </para>
210   </sect2>
211
212
213   <sect2 id="sql-syntax-constants">
214    <title>Constants</title>
215
216    <indexterm zone="sql-syntax-constants">
217     <primary>constant</primary>
218    </indexterm>
219
220    <para>
221     There are three kinds of <firstterm>implicitly-typed
222     constants</firstterm> in <productname>PostgreSQL</productname>:
223     strings, bit strings, and numbers.
224     Constants can also be specified with explicit types, which can
225     enable more accurate representation and more efficient handling by
226     the system. The implicit constants are described below; explicit
227     constants are discussed afterwards.
228    </para>
229
230    <sect3 id="sql-syntax-strings">
231     <title>String Constants</title>
232
233     <indexterm zone="sql-syntax-strings">
234      <primary>character string</primary>
235      <secondary>constant</secondary>
236     </indexterm>
237
238     <para>
239      <indexterm>
240       <primary>quotation marks</primary>
241       <secondary>escaping</secondary>
242      </indexterm>
243      A string constant in SQL is an arbitrary sequence of characters
244      bounded by single quotes (<quote>'</quote>), e.g., <literal>'This
245      is a string'</literal>.  SQL allows single quotes to be embedded
246      in strings by typing two adjacent single quotes (e.g.,
247      <literal>'Dianne''s horse'</literal>).  In
248      <productname>PostgreSQL</productname> single quotes may
249      alternatively be escaped with a backslash (<quote>\</quote>,
250      e.g., <literal>'Dianne\'s horse'</literal>).
251     </para>
252
253     <para>
254      C-style backslash escapes are also available:
255      <literal>\b</literal> is a backspace, <literal>\f</literal> is a
256      form feed, <literal>\n</literal> is a newline,
257      <literal>\r</literal> is a carriage return, <literal>\t</literal>
258      is a tab, and <literal>\<replaceable>xxx</replaceable></literal>,
259      where <replaceable>xxx</replaceable> is an octal number, is a
260      byte with the corresponding code.  (It is your responsibility
261      that the byte sequences you create are valid characters in the
262      server character set encoding.)  Any other character following a
263      backslash is taken literally.  Thus, to include a backslash in a
264      string constant, type two backslashes.
265     </para>
266
267     <para>
268      The character with the code zero cannot be in a string constant.
269     </para>
270
271     <para>
272      Two string constants that are only separated by whitespace
273      <emphasis>with at least one newline</emphasis> are concatenated
274      and effectively treated as if the string had been written in one
275      constant.  For example:
276 <programlisting>
277 SELECT 'foo'
278 'bar';
279 </programlisting>
280      is equivalent to
281 <programlisting>
282 SELECT 'foobar';
283 </programlisting>
284      but
285 <programlisting>
286 SELECT 'foo'      'bar';
287 </programlisting>
288      is not valid syntax.  (This slightly bizarre behavior is specified
289      by <acronym>SQL</acronym>; <productname>PostgreSQL</productname> is
290      following the standard.)
291     </para>
292    </sect3>
293
294    <sect3 id="sql-syntax-bit-strings">
295     <title>Bit-String Constants</title>
296
297     <indexterm zone="sql-syntax-bit-strings">
298      <primary>bit string</primary>
299      <secondary>constant</secondary>
300     </indexterm>
301
302     <para>
303      Bit-string constants look like string constants with a
304      <literal>B</literal> (upper or lower case) immediately before the
305      opening quote (no intervening whitespace), e.g.,
306      <literal>B'1001'</literal>.  The only characters allowed within
307      bit-string constants are <literal>0</literal> and
308      <literal>1</literal>.
309     </para>
310
311     <para>
312      Alternatively, bit-string constants can be specified in hexadecimal
313      notation, using a leading <literal>X</literal> (upper or lower case),
314      e.g., <literal>X'1FF'</literal>.  This notation is equivalent to
315      a bit-string constant with four binary digits for each hexadecimal digit.
316     </para>
317
318     <para>
319      Both forms of bit-string constant can be continued
320      across lines in the same way as regular string constants.
321     </para>
322    </sect3>
323
324    <sect3>
325     <title>Numeric Constants</title>
326
327     <indexterm>
328      <primary>number</primary>
329      <secondary>constant</secondary>
330     </indexterm>
331
332     <para>
333      Numeric constants are accepted in these general forms:
334 <synopsis>
335 <replaceable>digits</replaceable>
336 <replaceable>digits</replaceable>.<optional><replaceable>digits</replaceable></optional><optional>e<optional>+-</optional><replaceable>digits</replaceable></optional>
337 <optional><replaceable>digits</replaceable></optional>.<replaceable>digits</replaceable><optional>e<optional>+-</optional><replaceable>digits</replaceable></optional>
338 <replaceable>digits</replaceable>e<optional>+-</optional><replaceable>digits</replaceable>
339 </synopsis>
340      where <replaceable>digits</replaceable> is one or more decimal
341      digits (0 through 9).  At least one digit must be before or after the
342      decimal point, if one is used.  At least one digit must follow the
343      exponent marker (<literal>e</literal>), if one is present.
344      There may not be any spaces or other characters embedded in the
345      constant.  Note that any leading plus or minus sign is not actually
346      considered part of the constant; it is an operator applied to the
347      constant.
348     </para>
349
350     <para>
351      These are some examples of valid numeric constants:
352 <literallayout>
353 42
354 3.5
355 4.
356 .001
357 5e2
358 1.925e-3
359 </literallayout>
360     </para>
361
362     <para>
363      <indexterm><primary>integer</primary></indexterm>
364      <indexterm><primary>bigint</primary></indexterm>
365      <indexterm><primary>numeric</primary></indexterm>
366      A numeric constant that contains neither a decimal point nor an
367      exponent is initially presumed to be type <type>integer</> if its
368      value fits in type <type>integer</> (32 bits); otherwise it is
369      presumed to be type <type>bigint</> if its
370      value fits in type <type>bigint</> (64 bits); otherwise it is
371      taken to be type <type>numeric</>.  Constants that contain decimal
372      points and/or exponents are always initially presumed to be type
373      <type>numeric</>.
374     </para>
375
376     <para>
377      The initially assigned data type of a numeric constant is just a
378      starting point for the type resolution algorithms.  In most cases
379      the constant will be automatically coerced to the most
380      appropriate type depending on context.  When necessary, you can
381      force a numeric value to be interpreted as a specific data type
382      by casting it.<indexterm><primary>type cast</primary></indexterm>
383      For example, you can force a numeric value to be treated as type
384      <type>real</> (<type>float4</>) by writing
385
386 <programlisting>
387 REAL '1.23'  -- string style
388 1.23::REAL   -- PostgreSQL (historical) style
389 </programlisting>
390      </para>
391     </sect3>
392
393    <sect3 id="sql-syntax-constants-generic">
394     <title>Constants of Other Types</title>
395
396     <indexterm>
397      <primary>data type</primary>
398      <secondary>constant</secondary>
399     </indexterm>
400
401     <para>
402      A constant of an <emphasis>arbitrary</emphasis> type can be
403      entered using any one of the following notations:
404 <synopsis>
405 <replaceable>type</replaceable> '<replaceable>string</replaceable>'
406 '<replaceable>string</replaceable>'::<replaceable>type</replaceable>
407 CAST ( '<replaceable>string</replaceable>' AS <replaceable>type</replaceable> )
408 </synopsis>
409      The string's text is passed to the input conversion
410      routine for the type called <replaceable>type</replaceable>. The
411      result is a constant of the indicated type.  The explicit type
412      cast may be omitted if there is no ambiguity as to the type the
413      constant must be (for example, when it is passed as an argument
414      to a non-overloaded function), in which case it is automatically
415      coerced.
416     </para>
417
418     <para>
419      It is also possible to specify a type coercion using a function-like
420      syntax:
421 <synopsis>
422 <replaceable>typename</replaceable> ( '<replaceable>string</replaceable>' )
423 </synopsis>
424      but not all type names may be used in this way; see <xref
425      linkend="sql-syntax-type-casts"> for details.
426     </para>
427
428     <para>
429      The <literal>::</literal>, <literal>CAST()</literal>, and
430      function-call syntaxes can also be used to specify run-time type
431      conversions of arbitrary expressions, as discussed in <xref
432      linkend="sql-syntax-type-casts">.  But the form
433      <literal><replaceable>type</replaceable> '<replaceable>string</replaceable>'</literal>
434      can only be used to specify the type of a literal constant.
435      Another restriction on
436      <literal><replaceable>type</replaceable> '<replaceable>string</replaceable>'</literal>
437      is that it does not work for array types; use <literal>::</literal>
438      or <literal>CAST()</literal> to specify the type of an array constant.
439     </para>
440    </sect3>
441   </sect2>
442
443   <sect2 id="sql-syntax-operators">
444    <title>Operators</title>
445
446    <indexterm zone="sql-syntax-operators">
447     <primary>operator</primary>
448     <secondary>syntax</secondary>
449    </indexterm>
450
451    <para>
452     An operator is a sequence of up to <symbol>NAMEDATALEN</symbol>-1
453     (63 by default) characters from the following list:
454 <literallayout>
455 + - * / &lt; &gt; = ~ ! @ # % ^ &amp; | ` ?
456 </literallayout>
457
458     There are a few restrictions on operator names, however:
459     <itemizedlist>
460      <listitem>
461       <para>
462        <literal>--</literal> and <literal>/*</literal> cannot appear
463        anywhere in an operator name, since they will be taken as the
464        start of a comment.
465       </para>
466      </listitem>
467
468      <listitem>
469       <para>
470        A multiple-character operator name cannot end in <literal>+</> or <literal>-</>,
471        unless the name also contains at least one of these characters:
472 <literallayout>
473 ~ ! @ # % ^ &amp; | ` ?
474 </literallayout>
475        For example, <literal>@-</literal> is an allowed operator name,
476        but <literal>*-</literal> is not.  This restriction allows
477        <productname>PostgreSQL</productname> to parse SQL-compliant
478        queries without requiring spaces between tokens.
479       </para>
480      </listitem>
481     </itemizedlist>
482    </para>
483
484    <para>
485     When working with non-SQL-standard operator names, you will usually
486     need to separate adjacent operators with spaces to avoid ambiguity.
487     For example, if you have defined a left unary operator named <literal>@</literal>,
488     you cannot write <literal>X*@Y</literal>; you must write
489     <literal>X* @Y</literal> to ensure that
490     <productname>PostgreSQL</productname> reads it as two operator names
491     not one.
492    </para>
493   </sect2>
494
495   <sect2>
496    <title>Special Characters</title>
497
498   <para>
499    Some characters that are not alphanumeric have a special meaning
500    that is different from being an operator.  Details on the usage can
501    be found at the location where the respective syntax element is
502    described.  This section only exists to advise the existence and
503    summarize the purposes of these characters.
504
505    <itemizedlist>
506     <listitem>
507      <para>
508       A dollar sign (<literal>$</literal>) followed by digits is used
509       to represent a positional parameter in the body of a function
510       definition or a prepared statement.  In other contexts the
511       dollar sign may be part of an identifier.
512      </para>
513     </listitem>
514
515     <listitem>
516      <para>
517       Parentheses (<literal>()</literal>) have their usual meaning to
518       group expressions and enforce precedence.  In some cases
519       parentheses are required as part of the fixed syntax of a
520       particular SQL command.
521      </para>
522     </listitem>
523
524     <listitem>
525      <para>
526       Brackets (<literal>[]</literal>) are used to select the elements
527       of an array.  See <xref linkend="arrays"> for more information
528       on arrays.
529      </para>
530     </listitem>
531
532     <listitem>
533      <para>
534       Commas (<literal>,</literal>) are used in some syntactical
535       constructs to separate the elements of a list.
536      </para>
537     </listitem>
538
539     <listitem>
540      <para>
541       The semicolon (<literal>;</literal>) terminates an SQL command.
542       It cannot appear anywhere within a command, except within a
543       string constant or quoted identifier.
544      </para>
545     </listitem>
546
547     <listitem>
548      <para>
549       The colon (<literal>:</literal>) is used to select
550       <quote>slices</quote> from arrays. (See <xref
551       linkend="arrays">.)  In certain SQL dialects (such as Embedded
552       SQL), the colon is used to prefix variable names.
553      </para>
554     </listitem>
555
556     <listitem>
557      <para>
558       The asterisk (<literal>*</literal>) has a special meaning when
559       used in the <command>SELECT</command> command or with the
560       <function>COUNT</function> aggregate function.
561      </para>
562     </listitem>
563
564     <listitem>
565      <para>
566       The period (<literal>.</literal>) is used in numeric
567       constants, and to separate schema, table, and column names.
568      </para>
569     </listitem>
570    </itemizedlist>
571
572    </para>
573   </sect2>
574
575   <sect2 id="sql-syntax-comments">
576    <title>Comments</title>
577
578    <indexterm zone="sql-syntax-comments">
579     <primary>comment</primary>
580     <secondary sortas="SQL">in SQL</secondary>
581    </indexterm>
582
583    <para>
584     A comment is an arbitrary sequence of characters beginning with
585     double dashes and extending to the end of the line, e.g.:
586 <programlisting>
587 -- This is a standard SQL comment
588 </programlisting>
589    </para>
590
591    <para>
592     Alternatively, C-style block comments can be used:
593 <programlisting>
594 /* multiline comment
595  * with nesting: /* nested block comment */
596  */
597 </programlisting>
598     where the comment begins with <literal>/*</literal> and extends to
599     the matching occurrence of <literal>*/</literal>. These block
600     comments nest, as specified in the SQL standard but unlike C, so that one can
601     comment out larger blocks of code that may contain existing block
602     comments.
603    </para>
604
605    <para>
606     A comment is removed from the input stream before further syntax
607     analysis and is effectively replaced by whitespace.
608    </para>
609   </sect2>
610
611   <sect2 id="sql-precedence">
612    <title>Lexical Precedence</title>
613
614    <indexterm zone="sql-precedence">
615     <primary>operator</primary>
616     <secondary>precedence</secondary>
617    </indexterm>
618
619    <para>
620     <xref linkend="sql-precedence-table"> shows the precedence and
621     associativity of the operators in <productname>PostgreSQL</>.
622     Most operators have the same precedence and are left-associative.
623     The precedence and associativity of the operators is hard-wired
624     into the parser.  This may lead to non-intuitive behavior; for
625     example the Boolean operators <literal>&lt;</> and
626     <literal>&gt;</> have a different precedence than the Boolean
627     operators <literal>&lt;=</> and <literal>&gt;=</>.  Also, you will
628     sometimes need to add parentheses when using combinations of
629     binary and unary operators.  For instance
630 <programlisting>
631 SELECT 5 ! - 6;
632 </programlisting>
633    will be parsed as
634 <programlisting>
635 SELECT 5 ! (- 6);
636 </programlisting>
637     because the parser has no idea -- until it is too late -- that
638     <token>!</token> is defined as a postfix operator, not an infix one.
639     To get the desired behavior in this case, you must write
640 <programlisting>
641 SELECT (5 !) - 6;
642 </programlisting>
643     This is the price one pays for extensibility.
644    </para>
645
646    <table id="sql-precedence-table">
647     <title>Operator Precedence (decreasing)</title>
648
649     <tgroup cols="3">
650      <thead>
651       <row>
652        <entry>Operator/Element</entry>
653        <entry>Associativity</entry>
654        <entry>Description</entry>
655       </row>
656      </thead>
657
658      <tbody>
659       <row>
660        <entry><token>.</token></entry>
661        <entry>left</entry>
662        <entry>table/column name separator</entry>
663       </row>
664
665       <row>
666        <entry><token>::</token></entry>
667        <entry>left</entry>
668        <entry><productname>PostgreSQL</productname>-style typecast</entry>
669       </row>
670
671       <row>
672        <entry><token>[</token> <token>]</token></entry>
673        <entry>left</entry>
674        <entry>array element selection</entry>
675       </row>
676
677       <row>
678        <entry><token>-</token></entry>
679        <entry>right</entry>
680        <entry>unary minus</entry>
681       </row>
682
683       <row>
684        <entry><token>^</token></entry>
685        <entry>left</entry>
686        <entry>exponentiation</entry>
687       </row>
688
689       <row>
690        <entry><token>*</token> <token>/</token> <token>%</token></entry>
691        <entry>left</entry>
692        <entry>multiplication, division, modulo</entry>
693       </row>
694
695       <row>
696        <entry><token>+</token> <token>-</token></entry>
697        <entry>left</entry>
698        <entry>addition, subtraction</entry>
699       </row>
700
701       <row>
702        <entry><token>IS</token></entry>
703        <entry></entry>
704        <entry><literal>IS TRUE</>, <literal>IS FALSE</>, <literal>IS UNKNOWN</>, <literal>IS NULL</></entry>
705       </row>
706
707       <row>
708        <entry><token>ISNULL</token></entry>
709        <entry></entry>
710        <entry>test for null</entry>
711       </row>
712
713       <row>
714        <entry><token>NOTNULL</token></entry>
715        <entry></entry>
716        <entry>test for not null</entry>
717       </row>
718
719       <row>
720        <entry>(any other)</entry>
721        <entry>left</entry>
722        <entry>all other native and user-defined operators</entry>
723       </row>
724
725       <row>
726        <entry><token>IN</token></entry>
727        <entry></entry>
728        <entry>set membership</entry>
729       </row>
730
731       <row>
732        <entry><token>BETWEEN</token></entry>
733        <entry></entry>
734        <entry>containment</entry>
735       </row>
736
737       <row>
738        <entry><token>OVERLAPS</token></entry>
739        <entry></entry>
740        <entry>time interval overlap</entry>
741       </row>
742
743       <row>
744        <entry><token>LIKE</token> <token>ILIKE</token> <token>SIMILAR</token></entry>
745        <entry></entry>
746        <entry>string pattern matching</entry>
747       </row>
748
749       <row>
750        <entry><token>&lt;</token> <token>&gt;</token></entry>
751        <entry></entry>
752        <entry>less than, greater than</entry>
753       </row>
754
755       <row>
756        <entry><token>=</token></entry>
757        <entry>right</entry>
758        <entry>equality, assignment</entry>
759       </row>
760
761       <row>
762        <entry><token>NOT</token></entry>
763        <entry>right</entry>
764        <entry>logical negation</entry>
765       </row>
766
767       <row>
768        <entry><token>AND</token></entry>
769        <entry>left</entry>
770        <entry>logical conjunction</entry>
771       </row>
772
773       <row>
774        <entry><token>OR</token></entry>
775        <entry>left</entry>
776        <entry>logical disjunction</entry>
777       </row>
778      </tbody>
779     </tgroup>
780    </table>
781
782    <para>
783     Note that the operator precedence rules also apply to user-defined
784     operators that have the same names as the built-in operators
785     mentioned above.  For example, if you define a
786     <quote>+</quote> operator for some custom data type it will have
787     the same precedence as the built-in <quote>+</quote> operator, no
788     matter what yours does.
789    </para>
790
791    <para>
792     When a schema-qualified operator name is used in the
793     <literal>OPERATOR</> syntax, as for example in
794 <programlisting>
795 SELECT 3 OPERATOR(pg_catalog.+) 4;
796 </programlisting>
797     the <literal>OPERATOR</> construct is taken to have the default precedence
798     shown in <xref linkend="sql-precedence-table"> for <quote>any other</> operator.  This is true no matter
799     which specific operator name appears inside <literal>OPERATOR()</>.
800    </para>
801   </sect2>
802  </sect1>
803
804  <sect1 id="sql-expressions">
805   <title>Value Expressions</title>
806
807   <indexterm zone="sql-expressions">
808    <primary>expression</primary>
809    <secondary>syntax</secondary>
810   </indexterm>
811
812   <indexterm zone="sql-expressions">
813    <primary>value expression</primary>
814   </indexterm>
815
816   <indexterm>
817    <primary>scalar</primary>
818    <see>expression</see>
819   </indexterm>
820
821   <para>
822    Value expressions are used in a variety of contexts, such
823    as in the target list of the <command>SELECT</command> command, as
824    new column values in <command>INSERT</command> or
825    <command>UPDATE</command>, or in search conditions in a number of
826    commands.  The result of a value expression is sometimes called a
827    <firstterm>scalar</firstterm>, to distinguish it from the result of
828    a table expression (which is a table).  Value expressions are
829    therefore also called <firstterm>scalar expressions</firstterm> (or
830    even simply <firstterm>expressions</firstterm>).  The expression
831    syntax allows the calculation of values from primitive parts using
832    arithmetic, logical, set, and other operations.
833   </para>
834
835   <para>
836    A value expression is one of the following:
837
838    <itemizedlist>
839     <listitem>
840      <para>
841       A constant or literal value; see <xref linkend="sql-syntax-constants">.
842      </para>
843     </listitem>
844
845     <listitem>
846      <para>
847       A column reference.
848      </para>
849     </listitem>
850
851     <listitem>
852      <para>
853       A positional parameter reference, in the body of a function definition
854       or prepared statement.
855      </para>
856     </listitem>
857
858     <listitem>
859      <para>
860       An operator invocation.
861      </para>
862     </listitem>
863
864     <listitem>
865      <para>
866       A function call.
867      </para>
868     </listitem>
869
870     <listitem>
871      <para>
872       An aggregate expression.
873      </para>
874     </listitem>
875
876     <listitem>
877      <para>
878       A type cast.
879      </para>
880     </listitem>
881
882     <listitem>
883      <para>
884       A scalar subquery.
885      </para>
886     </listitem>
887
888     <listitem>
889      <para>
890       An array constructor.
891      </para>
892     </listitem>
893
894     <listitem>
895      <para>
896       Another value expression in parentheses, useful to group
897       subexpressions and override
898       precedence.<indexterm><primary>parenthesis</></>
899      </para>
900     </listitem>
901    </itemizedlist>
902   </para>
903
904   <para>
905    In addition to this list, there are a number of constructs that can
906    be classified as an expression but do not follow any general syntax
907    rules.  These generally have the semantics of a function or
908    operator and are explained in the appropriate location in <xref
909    linkend="functions">.  An example is the <literal>IS NULL</literal>
910    clause.
911   </para>
912
913   <para>
914    We have already discussed constants in <xref
915    linkend="sql-syntax-constants">.  The following sections discuss
916    the remaining options.
917   </para>
918
919   <sect2>
920    <title>Column References</title>
921
922    <indexterm>
923     <primary>column reference</primary>
924    </indexterm>
925
926    <para>
927     A column can be referenced in the form
928 <synopsis>
929 <replaceable>correlation</replaceable>.<replaceable>columnname</replaceable>
930 </synopsis>
931     or
932 <synopsis>
933 <replaceable>correlation</replaceable>.<replaceable>columnname</replaceable>[<replaceable>subscript</replaceable>]
934 </synopsis>
935     (Here, the brackets <literal>[ ]</literal> are meant to appear literally.)
936    </para>
937
938    <para>
939     <replaceable>correlation</replaceable> is the name of a
940     table (possibly qualified), or an alias for a table defined by means of a
941     <literal>FROM</literal> clause, or 
942     the key words <literal>NEW</literal> or <literal>OLD</literal>.
943     (<literal>NEW</literal> and <literal>OLD</literal> can only appear in rewrite rules,
944     while other correlation names can be used in any SQL statement.)
945     The correlation name and separating dot may be omitted if the column name
946     is unique across all the tables being used in the current query.  (See also <xref linkend="queries">.)
947    </para>
948
949    <para>
950     If <replaceable>column</replaceable> is of an array type, then the
951     optional <replaceable>subscript</replaceable> selects a specific
952     element or elements in the array.  If no subscript is provided, then the
953     whole array is selected.  (See <xref linkend="arrays"> for more about
954     arrays.)
955    </para>
956   </sect2>
957
958   <sect2>
959    <title>Positional Parameters</title>
960
961    <indexterm>
962     <primary>parameter</primary>
963     <secondary>syntax</secondary>
964    </indexterm>
965
966    <indexterm>
967     <primary>$</primary>
968    </indexterm>
969
970    <para>
971     A positional parameter reference is used to indicate a value
972     that is supplied externally to an SQL statement.  Parameters are
973     used in SQL function definitions and in prepared queries.  Some
974     client libraries also support specifying data values separately
975     from the SQL command string, in which case parameters are used to
976     refer to the out-of-line data values.
977     The form of a parameter reference is:
978 <synopsis>
979 $<replaceable>number</replaceable>
980 </synopsis>
981    </para>
982
983    <para>
984     For example, consider the definition of a function,
985     <function>dept</function>, as
986
987 <programlisting>
988 CREATE FUNCTION dept(text) RETURNS dept
989     AS 'SELECT * FROM dept WHERE name = $1'
990     LANGUAGE SQL;
991 </programlisting>
992
993     Here the <literal>$1</literal> will be replaced by the first
994     function argument when the function is invoked.
995    </para>
996   </sect2>
997
998   <sect2>
999    <title>Operator Invocations</title>
1000
1001    <indexterm>
1002     <primary>operator</primary>
1003     <secondary>invocation</secondary>
1004    </indexterm>
1005
1006    <para>
1007     There are three possible syntaxes for an operator invocation:
1008     <simplelist>
1009      <member><replaceable>expression</replaceable> <replaceable>operator</replaceable> <replaceable>expression</replaceable> (binary infix operator)</member>
1010      <member><replaceable>operator</replaceable> <replaceable>expression</replaceable> (unary prefix operator)</member>
1011      <member><replaceable>expression</replaceable> <replaceable>operator</replaceable> (unary postfix operator)</member>
1012     </simplelist>
1013     where the <replaceable>operator</replaceable> token follows the syntax
1014     rules of <xref linkend="sql-syntax-operators">, or is one of the
1015     key words <token>AND</token>, <token>OR</token>, and
1016     <token>NOT</token>, or is a qualified operator name
1017 <synopsis>
1018 <literal>OPERATOR(</><replaceable>schema</><literal>.</><replaceable>operatorname</><literal>)</>
1019 </synopsis>
1020     Which particular operators exist and whether
1021     they are unary or binary depends on what operators have been
1022     defined by the system or the user.  <xref linkend="functions">
1023     describes the built-in operators.
1024    </para>
1025   </sect2>
1026
1027   <sect2>
1028    <title>Function Calls</title>
1029
1030    <indexterm>
1031     <primary>function</primary>
1032     <secondary>invocation</secondary>
1033    </indexterm>
1034
1035    <para>
1036     The syntax for a function call is the name of a function
1037     (possibly qualified with a schema name), followed by its argument list
1038     enclosed in parentheses:
1039
1040 <synopsis>
1041 <replaceable>function</replaceable> (<optional><replaceable>expression</replaceable> <optional>, <replaceable>expression</replaceable> ... </optional></optional> )
1042 </synopsis>
1043    </para>
1044
1045    <para>
1046     For example, the following computes the square root of 2:
1047 <programlisting>
1048 sqrt(2)
1049 </programlisting>
1050    </para>
1051
1052    <para>
1053     The list of built-in functions is in <xref linkend="functions">.
1054     Other functions may be added by the user.
1055    </para>
1056   </sect2>
1057
1058   <sect2 id="syntax-aggregates">
1059    <title>Aggregate Expressions</title>
1060
1061    <indexterm zone="syntax-aggregates">
1062     <primary>aggregate function</primary>
1063     <secondary>invocation</secondary>
1064    </indexterm>
1065
1066    <para>
1067     An <firstterm>aggregate expression</firstterm> represents the
1068     application of an aggregate function across the rows selected by a
1069     query.  An aggregate function reduces multiple inputs to a single
1070     output value, such as the sum or average of the inputs.  The
1071     syntax of an aggregate expression is one of the following:
1072
1073 <synopsis>
1074 <replaceable>aggregate_name</replaceable> (<replaceable>expression</replaceable>)
1075 <replaceable>aggregate_name</replaceable> (ALL <replaceable>expression</replaceable>)
1076 <replaceable>aggregate_name</replaceable> (DISTINCT <replaceable>expression</replaceable>)
1077 <replaceable>aggregate_name</replaceable> ( * )
1078 </synopsis>
1079
1080     where <replaceable>aggregate_name</replaceable> is a previously
1081     defined aggregate (possibly a qualified name), and
1082     <replaceable>expression</replaceable> is 
1083     any value expression that does not itself contain an aggregate
1084     expression.
1085    </para>
1086
1087    <para>
1088     The first form of aggregate expression invokes the aggregate
1089     across all input rows for which the given expression yields a
1090     non-null value.  (Actually, it is up to the aggregate function
1091     whether to ignore null values or not --- but all the standard ones do.)
1092     The second form is the same as the first, since
1093     <literal>ALL</literal> is the default.  The third form invokes the
1094     aggregate for all distinct non-null values of the expression found
1095     in the input rows.  The last form invokes the aggregate once for
1096     each input row regardless of null or non-null values; since no
1097     particular input value is specified, it is generally only useful
1098     for the <function>count()</function> aggregate function.
1099    </para>
1100
1101    <para>
1102     For example, <literal>count(*)</literal> yields the total number
1103     of input rows; <literal>count(f1)</literal> yields the number of
1104     input rows in which <literal>f1</literal> is non-null;
1105     <literal>count(distinct f1)</literal> yields the number of
1106     distinct non-null values of <literal>f1</literal>.
1107    </para>
1108
1109    <para>
1110     The predefined aggregate functions are described in <xref
1111     linkend="functions-aggregate">.  Other aggregate functions may be added
1112     by the user. 
1113    </para>
1114
1115    <para>
1116     An aggregate expression may only appear in the result list or
1117     <literal>HAVING</> clause of a <command>SELECT</> command.
1118     It is forbidden in other clauses, such as <literal>WHERE</>,
1119     because those clauses are logically evaluated before the results
1120     of aggregates are formed.
1121    </para>
1122
1123    <para>
1124     When an aggregate expression appears in a subquery (see
1125     <xref linkend="sql-syntax-scalar-subqueries"> and
1126     <xref linkend="functions-subquery">), the aggregate is normally
1127     evaluated over the rows of the subquery.  But an exception occurs
1128     if the aggregate's argument contains only outer-level variables:
1129     the aggregate then belongs to the nearest such outer level, and is
1130     evaluated over the rows of that query.  The aggregate expression
1131     as a whole is then an outer reference for the subquery it appears in,
1132     and acts as a constant over any one evaluation of that subquery.
1133     The restriction about
1134     appearing only in the result list or <literal>HAVING</> clause
1135     applies with respect to the query level that the aggregate belongs to.
1136    </para>
1137   </sect2>
1138
1139   <sect2 id="sql-syntax-type-casts">
1140    <title>Type Casts</title>
1141
1142    <indexterm>
1143     <primary>data type</primary>
1144     <secondary>type cast</secondary>
1145    </indexterm>
1146
1147    <indexterm>
1148     <primary>type cast</primary>
1149    </indexterm>
1150
1151    <para>
1152     A type cast specifies a conversion from one data type to another.
1153     <productname>PostgreSQL</productname> accepts two equivalent syntaxes
1154     for type casts:
1155 <synopsis>
1156 CAST ( <replaceable>expression</replaceable> AS <replaceable>type</replaceable> )
1157 <replaceable>expression</replaceable>::<replaceable>type</replaceable>
1158 </synopsis>
1159     The <literal>CAST</> syntax conforms to SQL; the syntax with
1160     <literal>::</literal> is historical <productname>PostgreSQL</productname>
1161     usage.
1162    </para>
1163
1164    <para>
1165     When a cast is applied to a value expression of a known type, it
1166     represents a run-time type conversion.  The cast will succeed only
1167     if a suitable type conversion function is available.  Notice that this
1168     is subtly different from the use of casts with constants, as shown in
1169     <xref linkend="sql-syntax-constants-generic">.  A cast applied to an
1170     unadorned string literal represents the initial assignment of a type
1171     to a literal constant value, and so it will succeed for any type
1172     (if the contents of the string literal are acceptable input syntax for the
1173     data type).
1174    </para>
1175
1176    <para>
1177     An explicit type cast may usually be omitted if there is no ambiguity as
1178     to the type that a value expression must produce (for example, when it is
1179     assigned to a table column); the system will automatically apply a
1180     type cast in such cases.  However, automatic casting is only done for
1181     casts that are marked <quote>OK to apply implicitly</>
1182     in the system catalogs.  Other casts must be invoked with
1183     explicit casting syntax.  This restriction is intended to prevent
1184     surprising conversions from being applied silently.
1185    </para>
1186
1187    <para>
1188     It is also possible to specify a type cast using a function-like
1189     syntax:
1190 <synopsis>
1191 <replaceable>typename</replaceable> ( <replaceable>expression</replaceable> )
1192 </synopsis>
1193     However, this only works for types whose names are also valid as
1194     function names.  For example, <literal>double precision</literal>
1195     can't be used this way, but the equivalent <literal>float8</literal>
1196     can.  Also, the names <literal>interval</>, <literal>time</>, and
1197     <literal>timestamp</> can only be used in this fashion if they are
1198     double-quoted, because of syntactic conflicts.  Therefore, the use of
1199     the function-like cast syntax leads to inconsistencies and should
1200     probably be avoided in new applications.
1201
1202     (The function-like syntax is in fact just a function call.  When
1203     one of the two standard cast syntaxes is used to do a run-time
1204     conversion, it will internally invoke a registered function to
1205     perform the conversion.  By convention, these conversion functions
1206     have the same name as their output type, and thus the <quote>function-like
1207     syntax</> is nothing more than a direct invocation of the underlying
1208     conversion function.  Obviously, this is not something that a portable
1209     application should rely on.)
1210    </para>
1211   </sect2>
1212
1213   <sect2 id="sql-syntax-scalar-subqueries">
1214    <title>Scalar Subqueries</title>
1215
1216    <indexterm>
1217     <primary>subquery</primary>
1218    </indexterm>
1219
1220    <para>
1221     A scalar subquery is an ordinary
1222     <command>SELECT</command> query in parentheses that returns exactly one
1223     row with one column.  (See <xref linkend="queries"> for information about writing queries.)
1224     The <command>SELECT</command> query is executed
1225     and the single returned value is used in the surrounding value expression.
1226     It is an error to use a query that
1227     returns more than one row or more than one column as a scalar subquery.
1228     (But if, during a particular execution, the subquery returns no rows,
1229     there is no error; the scalar result is taken to be null.)
1230     The subquery can refer to variables from the surrounding query,
1231     which will act as constants during any one evaluation of the subquery.
1232     See also <xref linkend="functions-subquery"> for other expressions involving subqueries.
1233    </para>
1234
1235    <para>
1236     For example, the following finds the largest city population in each
1237     state:
1238 <programlisting>
1239 SELECT name, (SELECT max(pop) FROM cities WHERE cities.state = states.name)
1240     FROM states;
1241 </programlisting>
1242    </para>
1243   </sect2>
1244
1245   <sect2 id="sql-syntax-array-constructors">
1246    <title>Array Constructors</title>
1247
1248    <indexterm>
1249     <primary>array</primary>
1250     <secondary>constructor</secondary>
1251    </indexterm>
1252
1253    <para>
1254     An array constructor is an expression that builds an
1255     array value from values for its member elements.  A simple array
1256     constructor 
1257     consists of the key word <literal>ARRAY</literal>, a left square bracket
1258     <literal>[</>, one or more expressions (separated by commas) for the
1259     array element values, and finally a right square bracket <literal>]</>.
1260     For example,
1261 <programlisting>
1262 SELECT ARRAY[1,2,3+4];
1263   array
1264 ---------
1265  {1,2,7}
1266 (1 row)
1267 </programlisting>
1268     The array element type is the common type of the member expressions,
1269     determined using the same rules as for <literal>UNION</> or
1270     <literal>CASE</> constructs (see <xref linkend="typeconv-union-case">). 
1271    </para>
1272
1273    <para>
1274     Multidimensional array values can be built by nesting array
1275     constructors.
1276     In the inner constructors, the key word <literal>ARRAY</literal> may
1277     be omitted.  For example, these produce the same result:
1278
1279 <programlisting>
1280 SELECT ARRAY[ARRAY[1,2], ARRAY[3,4]];
1281      array
1282 ---------------
1283  {{1,2},{3,4}}
1284 (1 row)
1285
1286 SELECT ARRAY[[1,2],[3,4]];
1287      array
1288 ---------------
1289  {{1,2},{3,4}}
1290 (1 row)
1291 </programlisting>
1292
1293     Since multidimensional arrays must be rectangular, inner constructors
1294     at the same level must produce sub-arrays of identical dimensions.
1295   </para>
1296
1297   <para>
1298     Multidimensional array constructor elements can be anything yielding
1299     an array of the proper kind, not only a sub-<literal>ARRAY</> construct.
1300     For example:
1301 <programlisting>
1302 CREATE TABLE arr(f1 int[], f2 int[]);
1303
1304 INSERT INTO arr VALUES (ARRAY[[1,2],[3,4]], ARRAY[[5,6],[7,8]]);
1305
1306 SELECT ARRAY[f1, f2, '{{9,10},{11,12}}'::int[]] FROM arr;
1307                      array
1308 ------------------------------------------------
1309  {{{1,2},{3,4}},{{5,6},{7,8}},{{9,10},{11,12}}}
1310 (1 row)
1311 </programlisting>
1312   </para>
1313
1314   <para>
1315    It is also possible to construct an array from the results of a
1316    subquery.  In this form, the array constructor is written with the
1317    key word <literal>ARRAY</literal> followed by a parenthesized (not
1318    bracketed) subquery. For example:
1319 <programlisting>
1320 SELECT ARRAY(SELECT oid FROM pg_proc WHERE proname LIKE 'bytea%');
1321                           ?column?
1322 -------------------------------------------------------------
1323  {2011,1954,1948,1952,1951,1244,1950,2005,1949,1953,2006,31}
1324 (1 row)
1325 </programlisting>
1326    The subquery must return a single column. The resulting
1327    one-dimensional array will have an element for each row in the
1328    subquery result, with an element type matching that of the
1329    subquery's output column.
1330   </para>
1331
1332   <para>
1333    The subscripts of an array value built with <literal>ARRAY</literal>
1334    always begin with one.  For more information about arrays, see
1335    <xref linkend="arrays">.
1336   </para>
1337
1338   </sect2>
1339
1340   <sect2 id="syntax-express-eval">
1341    <title>Expression Evaluation Rules</title>
1342
1343    <indexterm>
1344     <primary>expression</primary>
1345     <secondary>order of evaluation</secondary>
1346    </indexterm>
1347
1348    <para>
1349     The order of evaluation of subexpressions is not defined.  In
1350     particular, the inputs of an operator or function are not necessarily
1351     evaluated left-to-right or in any other fixed order.
1352    </para>
1353
1354    <para>
1355     Furthermore, if the result of an expression can be determined by
1356     evaluating only some parts of it, then other subexpressions
1357     might not be evaluated at all.  For instance, if one wrote
1358 <programlisting>
1359 SELECT true OR somefunc();
1360 </programlisting>
1361     then <literal>somefunc()</literal> would (probably) not be called
1362     at all. The same would be the case if one wrote
1363 <programlisting>
1364 SELECT somefunc() OR true;
1365 </programlisting>
1366     Note that this is not the same as the left-to-right
1367     <quote>short-circuiting</quote> of Boolean operators that is found
1368     in some programming languages.
1369    </para>
1370
1371    <para>
1372     As a consequence, it is unwise to use functions with side effects
1373     as part of complex expressions.  It is particularly dangerous to
1374     rely on side effects or evaluation order in <literal>WHERE</> and <literal>HAVING</> clauses,
1375     since those clauses are extensively reprocessed as part of
1376     developing an execution plan.  Boolean
1377     expressions (<literal>AND</>/<literal>OR</>/<literal>NOT</> combinations) in those clauses may be reorganized
1378     in any manner allowed by the laws of Boolean algebra.
1379    </para>
1380
1381    <para>
1382     When it is essential to force evaluation order, a <literal>CASE</>
1383     construct (see <xref linkend="functions-conditional">) may be
1384     used.  For example, this is an untrustworthy way of trying to
1385     avoid division by zero in a <literal>WHERE</> clause:
1386 <programlisting>
1387 SELECT ... WHERE x &lt;&gt; 0 AND y/x &gt; 1.5;
1388 </programlisting>
1389     But this is safe:
1390 <programlisting>
1391 SELECT ... WHERE CASE WHEN x &lt;&gt; 0 THEN y/x &gt; 1.5 ELSE false END;
1392 </programlisting>
1393     A <literal>CASE</> construct used in this fashion will defeat optimization
1394     attempts, so it should only be done when necessary.  (In this particular
1395     example, it would doubtless be best to sidestep the problem by writing
1396     <literal>y &gt; 1.5*x</> instead.)
1397    </para>
1398   </sect2>
1399  </sect1>
1400
1401 </chapter>
1402
1403 <!-- Keep this comment at the end of the file
1404 Local variables:
1405 mode:sgml
1406 sgml-omittag:nil
1407 sgml-shorttag:t
1408 sgml-minimize-attributes:nil
1409 sgml-always-quote-attributes:t
1410 sgml-indent-step:1
1411 sgml-indent-data:t
1412 sgml-parent-document:nil
1413 sgml-default-dtd-file:"./reference.ced"
1414 sgml-exposed-tags:nil
1415 sgml-local-catalogs:("/usr/lib/sgml/catalog")
1416 sgml-local-ecat-files:nil
1417 End:
1418 -->