syntax.sgml 58.4 KB
Newer Older
1
<!-- $PostgreSQL: pgsql/doc/src/sgml/syntax.sgml,v 1.109 2006/09/16 00:30:16 momjian Exp $ -->
2

3 4
<chapter id="sql-syntax">
 <title>SQL Syntax</title>
5

6 7 8 9 10
 <indexterm zone="sql-syntax">
  <primary>syntax</primary>
  <secondary>SQL</secondary>
 </indexterm>

11 12 13 14 15 16 17 18 19 20 21 22
 <para>
  This chapter describes the syntax of SQL.  It forms the foundation
  for understanding the following chapters which will go into detail
  about how the SQL commands are applied to define and modify data.
 </para>

 <para>
  We also advise users who are already familiar with SQL to read this
  chapter carefully because there are several rules and concepts that
  are implemented inconsistently among SQL databases or that are
  specific to <productname>PostgreSQL</productname>.
 </para>
23

24 25 26
 <sect1 id="sql-syntax-lexical">
  <title>Lexical Structure</title>

P
Peter Eisentraut 已提交
27 28 29 30
  <indexterm>
   <primary>token</primary>
  </indexterm>

31
  <para>
32 33
   SQL input consists of a sequence of
   <firstterm>commands</firstterm>.  A command is composed of a
34 35 36 37
   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.
38 39
  </para>

40 41 42 43 44 45 46 47 48
  <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>
49

50 51 52 53 54 55
  <para>
   Additionally, <firstterm>comments</firstterm> can occur in SQL
   input.  They are not tokens, they are effectively equivalent to
   whitespace.
  </para>

56
   <para>
57
    For example, the following is (syntactically) valid SQL input:
58 59 60 61 62 63 64
<programlisting>
SELECT * FROM MY_TABLE;
UPDATE MY_TABLE SET A = 5;
INSERT INTO MY_TABLE VALUES (3, 'hi there');
</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
65
    commands can usefully be split across lines).
66
   </para>
67 68 69 70 71 72 73 74 75 76 77

  <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
78
   precise syntax rules for each command are described in <xref linkend="reference">.
79 80 81 82
  </para>

  <sect2 id="sql-syntax-identifiers">
   <title>Identifiers and Key Words</title>
83

84
   <indexterm zone="sql-syntax-identifiers">
P
Peter Eisentraut 已提交
85 86
    <primary>identifier</primary>
    <secondary>syntax of</secondary>
87 88 89
   </indexterm>

   <indexterm zone="sql-syntax-identifiers">
P
Peter Eisentraut 已提交
90 91 92 93 94 95 96
    <primary>name</primary>
    <secondary>syntax of</secondary>
   </indexterm>

   <indexterm zone="sql-syntax-identifiers">
    <primary>key word</primary>
    <secondary>syntax of</secondary>
97 98
   </indexterm>

99
   <para>
100 101 102 103 104 105 106 107 108 109 110 111 112
    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">.
113 114 115
   </para>

   <para>
116
    SQL identifiers and key words must begin with a letter
P
Peter Eisentraut 已提交
117 118
    (<literal>a</literal>-<literal>z</literal>, but also letters with
    diacritical marks and non-Latin letters) or an underscore
119
    (<literal>_</literal>).  Subsequent characters in an identifier or
120 121 122 123 124 125 126 127 128
    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
    according to the letter of the SQL standard, so their use may render
    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.
129 130
   </para>

131
   <para>
P
Peter Eisentraut 已提交
132
    <indexterm><primary>identifier</primary><secondary>length</secondary></indexterm>
133 134 135
    The system uses no more than <symbol>NAMEDATALEN</symbol>-1
    characters of an identifier; longer names can be written in
    commands, but they will be truncated.  By default,
B
Bruce Momjian 已提交
136
    <symbol>NAMEDATALEN</symbol> is 64 so the maximum identifier
137 138 139
    length is 63. If this limit is problematic, it can be raised by
    changing the <symbol>NAMEDATALEN</symbol> constant in
    <filename>src/include/postgres_ext.h</filename>.
140
   </para>
141

142
   <para>
143 144
    <indexterm>
     <primary>case sensitivity</primary>
P
Peter Eisentraut 已提交
145
     <secondary>of SQL commands</secondary>
146
    </indexterm>
147 148 149 150 151 152 153 154
    Identifier and key word names are case insensitive.  Therefore
<programlisting>
UPDATE MY_TABLE SET A = 5;
</programlisting>
    can equivalently be written as
<programlisting>
uPDaTE my_TabLE SeT a = 5;
</programlisting>
155
    A convention often used is to write key words in upper
156 157 158 159
    case and names in lower case, e.g.,
<programlisting>
UPDATE my_table SET a = 5;
</programlisting>
160 161 162
   </para>

   <para>
163
    <indexterm>
P
Peter Eisentraut 已提交
164
     <primary>quotation marks</primary>
165 166
     <secondary>and identifiers</secondary>
    </indexterm>
167 168 169 170 171 172 173 174
    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
175
    <literal>select</literal> would be taken as a key word and
176 177
    would therefore provoke a parse error when used where a table or
    column name is expected.  The example can be written with quoted
178
    identifiers like this:
179 180 181
<programlisting>
UPDATE "my_table" SET "a" = 5;
</programlisting>
182 183 184
   </para>

   <para>
185
    Quoted identifiers can contain any character other than a double
186
    quote itself.  (To include a double quote, write two double quotes.)
187 188
    This allows constructing table or column names that would
    otherwise not be possible, such as ones containing spaces or
189
    ampersands.  The length limitation still applies.
190
   </para>
191 192

   <para>
193 194
    Quoting an identifier also makes it case-sensitive, whereas
    unquoted names are always folded to lower case.  For example, the
195
    identifiers <literal>FOO</literal>, <literal>foo</literal>, and
196
    <literal>"foo"</literal> are considered the same by
P
Peter Eisentraut 已提交
197 198 199 200 201 202 203 204 205
    <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
T
Tom Lane 已提交
206
    particular name or never quote it.)
207
   </para>
208 209
  </sect2>

210

211
  <sect2 id="sql-syntax-constants">
212 213
   <title>Constants</title>

214
   <indexterm zone="sql-syntax-constants">
P
Peter Eisentraut 已提交
215
    <primary>constant</primary>
216 217
   </indexterm>

218
   <para>
219
    There are three kinds of <firstterm>implicitly-typed
220
    constants</firstterm> in <productname>PostgreSQL</productname>:
221
    strings, bit strings, and numbers.
222 223
    Constants can also be specified with explicit types, which can
    enable more accurate representation and more efficient handling by
224 225
    the system. These alternatives are discussed in the following
    subsections.
226 227
   </para>

228
   <sect3 id="sql-syntax-strings">
229 230
    <title>String Constants</title>

231
    <indexterm zone="sql-syntax-strings">
P
Peter Eisentraut 已提交
232 233
     <primary>character string</primary>
     <secondary>constant</secondary>
234 235
    </indexterm>

236
    <para>
237
     <indexterm>
P
Peter Eisentraut 已提交
238
      <primary>quotation marks</primary>
239 240
      <secondary>escaping</secondary>
     </indexterm>
241 242 243 244 245 246 247
     A string constant in SQL is an arbitrary sequence of characters
     bounded by single quotes (<literal>'</literal>), for example
     <literal>'This is a string'</literal>.  The standard-compliant way of
     writing a single-quote character within a string constant is to
     write two adjacent single quotes, e.g.
     <literal>'Dianne''s horse'</literal>.
     <productname>PostgreSQL</productname> also allows single quotes
248 249
     to be escaped with a backslash (<literal>\'</literal>).  However,
     future versions of <productname>PostgreSQL</productname> will not
250
     allow this, so applications using backslashes should convert to the 
251
     standard-compliant method outlined above.
252
    </para>
253 254

    <para>
255
     Another <productname>PostgreSQL</productname> extension is that
256 257 258 259 260
     C-style backslash escapes are available: <literal>\b</literal> is a
     backspace, <literal>\f</literal> is a form feed,
     <literal>\n</literal> is a newline, <literal>\r</literal> is a
     carriage return, <literal>\t</literal> is a tab. Also supported is
     <literal>\<replaceable>digits</replaceable></literal>, where
T
Tom Lane 已提交
261
     <replaceable>digits</replaceable> represents an octal byte value, and
262 263 264 265 266 267
     <literal>\x<replaceable>hexdigits</replaceable></literal>, where
     <replaceable>hexdigits</replaceable> represents a hexadecimal byte value.
     (It is your responsibility that the byte sequences you create are
     valid characters in the server character set encoding.) Any other
     character following a backslash is taken literally. Thus, to
     include a backslash in a string constant, write two backslashes.
268 269
    </para>

270 271 272 273 274
    <note>
    <para>
     While ordinary strings now support C-style backslash escapes,
     future versions will generate warnings for such usage and
     eventually treat backslashes as literal characters to be
275
     standard-conforming. The proper way to specify escape processing is
276
     to use the escape string syntax to indicate that escape
277 278
     processing is desired. Escape string syntax is specified by writing
     the letter <literal>E</literal> (upper or lower case) just before
279 280 281 282 283
     the string, e.g. <literal>E'\041'</>. This method will work in all
     future versions of <productname>PostgreSQL</productname>.
    </para>
    </note>

284 285 286
    <para>
     The character with the code zero cannot be in a string constant.
    </para>
287

288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
    <para>
     Two string constants that are only separated by whitespace
     <emphasis>with at least one newline</emphasis> are concatenated
     and effectively treated as if the string had been written in one
     constant.  For example:
<programlisting>
SELECT 'foo'
'bar';
</programlisting>
     is equivalent to
<programlisting>
SELECT 'foobar';
</programlisting>
     but
<programlisting>
SELECT 'foo'      'bar';
</programlisting>
305
     is not valid syntax.  (This slightly bizarre behavior is specified
306
     by <acronym>SQL</acronym>; <productname>PostgreSQL</productname> is
307
     following the standard.)
308 309 310
    </para>
   </sect3>

311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
   <sect3 id="sql-syntax-dollar-quoting">
    <title>Dollar-Quoted String Constants</title>

     <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>

391
   <sect3 id="sql-syntax-bit-strings">
P
Peter Eisentraut 已提交
392
    <title>Bit-String Constants</title>
393

394
    <indexterm zone="sql-syntax-bit-strings">
P
Peter Eisentraut 已提交
395 396
     <primary>bit string</primary>
     <secondary>constant</secondary>
397 398
    </indexterm>

399
    <para>
400
     Bit-string constants look like regular string constants with a
401 402 403
     <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
P
Peter Eisentraut 已提交
404
     bit-string constants are <literal>0</literal> and
405
     <literal>1</literal>.
406
    </para>
407

408 409 410 411
    <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
412
     a bit-string constant with four binary digits for each hexadecimal digit.
413
    </para>
414 415

    <para>
416 417
     Both forms of bit-string constant can be continued
     across lines in the same way as regular string constants.
418
     Dollar quoting cannot be used in a bit-string constant.
419 420
    </para>
   </sect3>
421

422
   <sect3>
423
    <title>Numeric Constants</title>
424

425
    <indexterm>
P
Peter Eisentraut 已提交
426 427
     <primary>number</primary>
     <secondary>constant</secondary>
428 429
    </indexterm>

430
    <para>
431
     Numeric constants are accepted in these general forms:
432
<synopsis>
433
<replaceable>digits</replaceable>
434 435 436 437 438
<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
439 440 441 442
     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.
     There may not be any spaces or other characters embedded in the
443
     constant.  Note that any leading plus or minus sign is not actually
444 445
     considered part of the constant; it is an operator applied to the
     constant.
446 447
    </para>

448
    <para>
449
     These are some examples of valid numeric constants:
450
<literallayout>
451
42
452 453 454 455 456
3.5
4.
.001
5e2
1.925e-3
457 458
</literallayout>
    </para>
459

460
    <para>
P
Peter Eisentraut 已提交
461 462 463
     <indexterm><primary>integer</primary></indexterm>
     <indexterm><primary>bigint</primary></indexterm>
     <indexterm><primary>numeric</primary></indexterm>
464 465 466 467 468
     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
469
     taken to be type <type>numeric</>.  Constants that contain decimal
470 471 472 473 474 475
     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
P
Peter Eisentraut 已提交
476 477 478 479 480 481 482
     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
     <type>real</> (<type>float4</>) by writing
483

484
<programlisting>
485
REAL '1.23'  -- string style
486
1.23::REAL   -- PostgreSQL (historical) style
487
</programlisting>
488 489 490 491 492

     These are actually just special cases of the general casting
     notations discussed next.
    </para>
   </sect3>
493

494
   <sect3 id="sql-syntax-constants-generic">
495
    <title>Constants of Other Types</title>
496

497
    <indexterm>
P
Peter Eisentraut 已提交
498 499
     <primary>data type</primary>
     <secondary>constant</secondary>
500 501
    </indexterm>

502
    <para>
503 504 505
     A constant of an <emphasis>arbitrary</emphasis> type can be
     entered using any one of the following notations:
<synopsis>
506 507
<replaceable>type</replaceable> '<replaceable>string</replaceable>'
'<replaceable>string</replaceable>'::<replaceable>type</replaceable>
508
CAST ( '<replaceable>string</replaceable>' AS <replaceable>type</replaceable> )
509
</synopsis>
510
     The string constant's text is passed to the input conversion
511 512 513
     routine for the type called <replaceable>type</replaceable>. The
     result is a constant of the indicated type.  The explicit type
     cast may be omitted if there is no ambiguity as to the type the
514 515 516 517 518 519 520
     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.
521
    </para>
522 523 524 525

    <para>
     It is also possible to specify a type coercion using a function-like
     syntax:
526
<synopsis>
527
<replaceable>typename</replaceable> ( '<replaceable>string</replaceable>' )
528
</synopsis>
529 530
     but not all type names may be used in this way; see <xref
     linkend="sql-syntax-type-casts"> for details.
531 532 533
    </para>

    <para>
534
     The <literal>::</literal>, <literal>CAST()</literal>, and
535
     function-call syntaxes can also be used to specify run-time type
536 537
     conversions of arbitrary expressions, as discussed in <xref
     linkend="sql-syntax-type-casts">.  But the form
538
     <literal><replaceable>type</replaceable> '<replaceable>string</replaceable>'</literal>
539 540
     can only be used to specify the type of a literal constant.
     Another restriction on
541
     <literal><replaceable>type</replaceable> '<replaceable>string</replaceable>'</literal>
542 543
     is that it does not work for array types; use <literal>::</literal>
     or <literal>CAST()</literal> to specify the type of an array constant.
544
    </para>
T
Tom Lane 已提交
545 546 547 548 549

    <para>
     The <literal>CAST()</> syntax conforms to SQL.  The
     <literal><replaceable>type</replaceable> '<replaceable>string</replaceable>'</literal>
     syntax is a generalization of the standard: SQL specifies this syntax only
550
     for a few data types, but <productname>PostgreSQL</productname> allows it
T
Tom Lane 已提交
551 552 553 554
     for all types.  The syntax with
     <literal>::</literal> is historical <productname>PostgreSQL</productname>
     usage, as is the function-call syntax.
    </para>
555 556 557 558 559 560
   </sect3>
  </sect2>

  <sect2 id="sql-syntax-operators">
   <title>Operators</title>

561
   <indexterm zone="sql-syntax-operators">
P
Peter Eisentraut 已提交
562
    <primary>operator</primary>
563 564 565
    <secondary>syntax</secondary>
   </indexterm>

566
   <para>
567
    An operator name is a sequence of up to <symbol>NAMEDATALEN</symbol>-1
568
    (63 by default) characters from the following list:
569
<literallayout>
570
+ - * / &lt; &gt; = ~ ! @ # % ^ &amp; | ` ?
571 572 573 574 575 576 577 578 579 580 581 582 583 584
</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>
585
       A multiple-character operator name cannot end in <literal>+</> or <literal>-</>,
586 587
       unless the name also contains at least one of these characters:
<literallayout>
588
~ ! @ # % ^ &amp; | ` ?
589 590 591
</literallayout>
       For example, <literal>@-</literal> is an allowed operator name,
       but <literal>*-</literal> is not.  This restriction allows
592
       <productname>PostgreSQL</productname> to parse SQL-compliant
593 594 595 596 597 598 599 600 601
       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.
P
Peter Eisentraut 已提交
602
    For example, if you have defined a left unary operator named <literal>@</literal>,
603 604
    you cannot write <literal>X*@Y</literal>; you must write
    <literal>X* @Y</literal> to ensure that
605
    <productname>PostgreSQL</productname> reads it as two operator names
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
    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
624
      to represent a positional parameter in the body of a function
625
      definition or a prepared statement.  In other contexts the
626 627
      dollar sign may be part of an identifier or a dollar-quoted string
      constant.
628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
     </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.
658 659
      It cannot appear anywhere within a command, except within a
      string constant or quoted identifier.
660 661 662 663 664 665 666 667 668 669 670 671 672 673
     </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>
674 675
      The asterisk (<literal>*</literal>) is used in some contexts to denote
      all the fields of a table row or composite value.  It also
676 677 678
      has a special meaning when used as the argument of an
      aggregate function, namely that the aggregate does not require
      any explicit parameter.
679 680 681 682 683
     </para>
    </listitem>

    <listitem>
     <para>
684
      The period (<literal>.</literal>) is used in numeric
685
      constants, and to separate schema, table, and column names.
686 687 688 689 690 691 692 693 694 695
     </para>
    </listitem>
   </itemizedlist>

   </para>
  </sect2>

  <sect2 id="sql-syntax-comments">
   <title>Comments</title>

696
   <indexterm zone="sql-syntax-comments">
P
Peter Eisentraut 已提交
697 698
    <primary>comment</primary>
    <secondary sortas="SQL">in SQL</secondary>
699 700
   </indexterm>

701 702 703 704
   <para>
    A comment is an arbitrary sequence of characters beginning with
    double dashes and extending to the end of the line, e.g.:
<programlisting>
P
Peter Eisentraut 已提交
705
-- This is a standard SQL comment
706 707 708 709 710 711
</programlisting>
   </para>

   <para>
    Alternatively, C-style block comments can be used:
<programlisting>
712
/* multiline comment
713 714 715 716 717
 * with nesting: /* nested block comment */
 */
</programlisting>
    where the comment begins with <literal>/*</literal> and extends to
    the matching occurrence of <literal>*/</literal>. These block
P
Peter Eisentraut 已提交
718
    comments nest, as specified in the SQL standard but unlike C, so that one can
719 720 721 722 723 724 725 726 727
    comment out larger blocks of code that may contain existing block
    comments.
   </para>

   <para>
    A comment is removed from the input stream before further syntax
    analysis and is effectively replaced by whitespace.
   </para>
  </sect2>
728 729 730 731 732

  <sect2 id="sql-precedence">
   <title>Lexical Precedence</title>

   <indexterm zone="sql-precedence">
P
Peter Eisentraut 已提交
733
    <primary>operator</primary>
734 735 736 737
    <secondary>precedence</secondary>
   </indexterm>

   <para>
738
    <xref linkend="sql-precedence-table"> shows the precedence and
B
Bruce Momjian 已提交
739 740 741 742 743 744 745 746 747
    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
    into the parser.  This may lead to non-intuitive behavior; for
    example the Boolean operators <literal>&lt;</> and
    <literal>&gt;</> have a different precedence than the Boolean
    operators <literal>&lt;=</> and <literal>&gt;=</>.  Also, you will
    sometimes need to add parentheses when using combinations of
    binary and unary operators.  For instance
748 749 750 751 752 753 754
<programlisting>
SELECT 5 ! - 6;
</programlisting>
   will be parsed as
<programlisting>
SELECT 5 ! (- 6);
</programlisting>
755 756 757 758
    because the parser has no idea &mdash; until it is too late
    &mdash; that <token>!</token> is defined as a postfix operator,
    not an infix one.  To get the desired behavior in this case, you
    must write
759 760 761 762 763 764
<programlisting>
SELECT (5 !) - 6;
</programlisting>
    This is the price one pays for extensibility.
   </para>

765
   <table id="sql-precedence-table">
766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
    <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>
P
Peter Eisentraut 已提交
823
       <entry><literal>IS TRUE</>, <literal>IS FALSE</>, <literal>IS UNKNOWN</>, <literal>IS NULL</></entry>
824 825 826 827 828
      </row>

      <row>
       <entry><token>ISNULL</token></entry>
       <entry></entry>
P
Peter Eisentraut 已提交
829
       <entry>test for null</entry>
830 831 832 833 834
      </row>

      <row>
       <entry><token>NOTNULL</token></entry>
       <entry></entry>
P
Peter Eisentraut 已提交
835
       <entry>test for not null</entry>
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852
      </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>
853
       <entry>range containment</entry>
854 855 856 857 858 859 860 861 862
      </row>

      <row>
       <entry><token>OVERLAPS</token></entry>
       <entry></entry>
       <entry>time interval overlap</entry>
      </row>

      <row>
863
       <entry><token>LIKE</token> <token>ILIKE</token> <token>SIMILAR</token></entry>
864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908
       <entry></entry>
       <entry>string pattern matching</entry>
      </row>

      <row>
       <entry><token>&lt;</token> <token>&gt;</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>
909 910 911 912 913 914 915 916

   <para>
    When a schema-qualified operator name is used in the
    <literal>OPERATOR</> syntax, as for example in
<programlisting>
SELECT 3 OPERATOR(pg_catalog.+) 4;
</programlisting>
    the <literal>OPERATOR</> construct is taken to have the default precedence
917
    shown in <xref linkend="sql-precedence-table"> for <quote>any other</> operator.  This is true no matter
918 919
    which specific operator name appears inside <literal>OPERATOR()</>.
   </para>
920
  </sect2>
921 922
 </sect1>

923 924
 <sect1 id="sql-expressions">
  <title>Value Expressions</title>
925

P
Peter Eisentraut 已提交
926 927 928 929 930 931 932 933 934 935 936 937 938 939
  <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>

940
  <para>
941
   Value expressions are used in a variety of contexts, such
942 943 944 945 946 947 948 949 950 951 952
   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>
953

954 955
  <para>
   A value expression is one of the following:
956

957 958 959
   <itemizedlist>
    <listitem>
     <para>
T
Tom Lane 已提交
960
      A constant or literal value.
961 962
     </para>
    </listitem>
963

964 965
    <listitem>
     <para>
966
      A column reference.
967 968
     </para>
    </listitem>
969

970 971
    <listitem>
     <para>
972 973
      A positional parameter reference, in the body of a function definition
      or prepared statement.
974 975
     </para>
    </listitem>
976

977 978 979 980 981 982 983 984 985 986 987 988
    <listitem>
     <para>
      A subscripted expression.
     </para>
    </listitem>

    <listitem>
     <para>
      A field selection expression.
     </para>
    </listitem>

989
    <listitem>
990
     <para>
991
      An operator invocation.
992 993
     </para>
    </listitem>
994

995 996
    <listitem>
     <para>
997
      A function call.
998 999
     </para>
    </listitem>
1000

1001 1002
    <listitem>
     <para>
1003
      An aggregate expression.
1004 1005
     </para>
    </listitem>
1006

1007 1008
    <listitem>
     <para>
1009
      A type cast.
1010 1011
     </para>
    </listitem>
1012

1013 1014
    <listitem>
     <para>
1015 1016 1017 1018
      A scalar subquery.
     </para>
    </listitem>

1019 1020 1021 1022 1023 1024
    <listitem>
     <para>
      An array constructor.
     </para>
    </listitem>

1025 1026 1027 1028 1029 1030
    <listitem>
     <para>
      A row constructor.
     </para>
    </listitem>

1031 1032
    <listitem>
     <para>
P
Peter Eisentraut 已提交
1033 1034 1035
      Another value expression in parentheses, useful to group
      subexpressions and override
      precedence.<indexterm><primary>parenthesis</></>
1036 1037 1038 1039
     </para>
    </listitem>
   </itemizedlist>
  </para>
1040

1041
  <para>
1042
   In addition to this list, there are a number of constructs that can
1043 1044 1045 1046 1047 1048
   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>
1049

1050 1051 1052 1053 1054
  <para>
   We have already discussed constants in <xref
   linkend="sql-syntax-constants">.  The following sections discuss
   the remaining options.
  </para>
1055

1056 1057
  <sect2>
   <title>Column References</title>
1058

P
Peter Eisentraut 已提交
1059 1060 1061 1062
   <indexterm>
    <primary>column reference</primary>
   </indexterm>

1063
   <para>
1064
    A column can be referenced in the form
1065
<synopsis>
1066
<replaceable>correlation</replaceable>.<replaceable>columnname</replaceable>
1067
</synopsis>
1068
   </para>
1069

1070
   <para>
T
Tom Lane 已提交
1071
    <replaceable>correlation</replaceable> is the name of a
1072 1073
    table (possibly qualified with a schema name), or an alias for a table
    defined by means of a <literal>FROM</literal> clause, or one of
P
Peter Eisentraut 已提交
1074
    the key words <literal>NEW</literal> or <literal>OLD</literal>.
1075
    (<literal>NEW</literal> and <literal>OLD</literal> can only appear in rewrite rules,
1076
    while other correlation names can be used in any SQL statement.)
1077
    The correlation name and separating dot may be omitted if the column name
1078 1079
    is unique across all the tables being used in the current query.  (See also <xref linkend="queries">.)
   </para>
1080
  </sect2>
1081

1082 1083
  <sect2>
   <title>Positional Parameters</title>
1084

P
Peter Eisentraut 已提交
1085 1086 1087 1088 1089 1090 1091 1092 1093
   <indexterm>
    <primary>parameter</primary>
    <secondary>syntax</secondary>
   </indexterm>

   <indexterm>
    <primary>$</primary>
   </indexterm>

1094
   <para>
1095
    A positional parameter reference is used to indicate a value
1096
    that is supplied externally to an SQL statement.  Parameters are
1097 1098 1099 1100
    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.
1101
    The form of a parameter reference is:
1102 1103 1104 1105
<synopsis>
$<replaceable>number</replaceable>
</synopsis>
   </para>
1106

1107 1108 1109
   <para>
    For example, consider the definition of a function,
    <function>dept</function>, as
1110

1111
<programlisting>
1112
CREATE FUNCTION dept(text) RETURNS dept
1113
    AS $$ SELECT * FROM dept WHERE name = $1 $$
1114
    LANGUAGE SQL;
1115
</programlisting>
1116

T
Tom Lane 已提交
1117 1118
    Here the <literal>$1</literal> references the value of the first
    function argument whenever the function is invoked.
1119 1120
   </para>
  </sect2>
1121

1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
  <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
    parenthesized, but the parentheses may be omitted when the expression
    to be subscripted is just a column reference or positional parameter.
    Also, multiple subscripts can be concatenated when the original array
1150
    is multidimensional.
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
    For example,

<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>

  <sect2>
   <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
    parenthesized, but the parentheses may be omitted when the expression
    to be selected from is just a table reference or positional parameter.
    For example,

<programlisting>
mytable.mycolumn
$1.somecolumn
(rowfunction(a,b)).col3
</programlisting>

    (Thus, a qualified column reference is actually just a special case
    of the field selection syntax.)
   </para>
  </sect2>

1197 1198 1199
  <sect2>
   <title>Operator Invocations</title>

P
Peter Eisentraut 已提交
1200 1201 1202 1203 1204
   <indexterm>
    <primary>operator</primary>
    <secondary>invocation</secondary>
   </indexterm>

1205 1206 1207 1208 1209 1210 1211 1212
   <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
T
Tom Lane 已提交
1213
    rules of <xref linkend="sql-syntax-operators">, or is one of the
1214
    key words <token>AND</token>, <token>OR</token>, and
1215
    <token>NOT</token>, or is a qualified operator name in the form
T
Tom Lane 已提交
1216
<synopsis>
1217
<literal>OPERATOR(</><replaceable>schema</><literal>.</><replaceable>operatorname</><literal>)</>
T
Tom Lane 已提交
1218 1219
</synopsis>
    Which particular operators exist and whether
1220 1221 1222 1223 1224 1225
    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>

1226 1227
  <sect2>
   <title>Function Calls</title>
1228

P
Peter Eisentraut 已提交
1229 1230 1231 1232 1233
   <indexterm>
    <primary>function</primary>
    <secondary>invocation</secondary>
   </indexterm>

1234
   <para>
1235
    The syntax for a function call is the name of a function
T
Tom Lane 已提交
1236
    (possibly qualified with a schema name), followed by its argument list
1237
    enclosed in parentheses:
1238

1239 1240 1241 1242
<synopsis>
<replaceable>function</replaceable> (<optional><replaceable>expression</replaceable> <optional>, <replaceable>expression</replaceable> ... </optional></optional> )
</synopsis>
   </para>
1243

1244 1245 1246 1247 1248 1249
   <para>
    For example, the following computes the square root of 2:
<programlisting>
sqrt(2)
</programlisting>
   </para>
1250

1251 1252 1253 1254 1255
   <para>
    The list of built-in functions is in <xref linkend="functions">.
    Other functions may be added by the user.
   </para>
  </sect2>
1256

1257 1258
  <sect2 id="syntax-aggregates">
   <title>Aggregate Expressions</title>
1259

1260
   <indexterm zone="syntax-aggregates">
P
Peter Eisentraut 已提交
1261 1262
    <primary>aggregate function</primary>
    <secondary>invocation</secondary>
1263 1264
   </indexterm>

1265 1266 1267 1268 1269 1270
   <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:
1271

1272
<synopsis>
1273 1274 1275
<replaceable>aggregate_name</replaceable> (<replaceable>expression</replaceable> [ , ... ] )
<replaceable>aggregate_name</replaceable> (ALL <replaceable>expression</replaceable> [ , ... ] )
<replaceable>aggregate_name</replaceable> (DISTINCT <replaceable>expression</replaceable> [ , ... ] )
1276 1277
<replaceable>aggregate_name</replaceable> ( * )
</synopsis>
1278

1279
    where <replaceable>aggregate_name</replaceable> is a previously
1280
    defined aggregate (possibly qualified with a schema name), and
T
Tom Lane 已提交
1281
    <replaceable>expression</replaceable> is 
1282
    any value expression that does not itself contain an aggregate
1283 1284
    expression.
   </para>
1285

1286 1287
   <para>
    The first form of aggregate expression invokes the aggregate
1288 1289
    across all input rows for which the given expression(s) yield
    non-null values.  (Actually, it is up to the aggregate function
1290
    whether to ignore null values or not &mdash; but all the standard ones do.)
1291
    The second form is the same as the first, since
1292
    <literal>ALL</literal> is the default.  The third form invokes the
1293
    aggregate for all distinct non-null values of the expressions found
1294
    in the input rows.  The last form invokes the aggregate once for
P
Peter Eisentraut 已提交
1295
    each input row regardless of null or non-null values; since no
1296
    particular input value is specified, it is generally only useful
1297
    for the <function>count(*)</function> aggregate function.
1298
   </para>
1299

1300 1301 1302
   <para>
    For example, <literal>count(*)</literal> yields the total number
    of input rows; <literal>count(f1)</literal> yields the number of
P
Peter Eisentraut 已提交
1303
    input rows in which <literal>f1</literal> is non-null;
1304
    <literal>count(distinct f1)</literal> yields the number of
P
Peter Eisentraut 已提交
1305
    distinct non-null values of <literal>f1</literal>.
1306
   </para>
1307

1308 1309
   <para>
    The predefined aggregate functions are described in <xref
1310 1311
    linkend="functions-aggregate">.  Other aggregate functions may be added
    by the user. 
1312
   </para>
1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326

   <para>
    An aggregate expression may only appear in the result list or
    <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
1327
    if the aggregate's arguments contain only outer-level variables:
1328 1329 1330 1331 1332 1333 1334 1335
    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>
1336 1337 1338 1339 1340 1341 1342

   <note>
    <para>
     <productname>PostgreSQL</productname> currently does not support
     <literal>DISTINCT</> with more than one input expression.
    </para>
   </note>
1343
  </sect2>
1344 1345 1346 1347

  <sect2 id="sql-syntax-type-casts">
   <title>Type Casts</title>

P
Peter Eisentraut 已提交
1348 1349 1350 1351 1352 1353 1354 1355
   <indexterm>
    <primary>data type</primary>
    <secondary>type cast</secondary>
   </indexterm>

   <indexterm>
    <primary>type cast</primary>
   </indexterm>
1356 1357

   <para>
P
Peter Eisentraut 已提交
1358
    A type cast specifies a conversion from one data type to another.
1359 1360 1361 1362 1363 1364
    <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>
1365
    The <literal>CAST</> syntax conforms to SQL; the syntax with
1366 1367 1368 1369 1370 1371 1372
    <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
1373
    if a suitable type conversion operation has been defined.  Notice that this
1374 1375 1376 1377
    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
P
Peter Eisentraut 已提交
1378 1379
    (if the contents of the string literal are acceptable input syntax for the
    data type).
1380 1381 1382
   </para>

   <para>
T
Tom Lane 已提交
1383 1384
    An explicit type cast may usually be omitted if there is no ambiguity as
    to the type that a value expression must produce (for example, when it is
1385
    assigned to a table column); the system will automatically apply a
T
Tom Lane 已提交
1386
    type cast in such cases.  However, automatic casting is only done for
1387 1388
    casts that are marked <quote>OK to apply implicitly</>
    in the system catalogs.  Other casts must be invoked with
T
Tom Lane 已提交
1389 1390
    explicit casting syntax.  This restriction is intended to prevent
    surprising conversions from being applied silently.
1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403
   </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>
    can't be used this way, but the equivalent <literal>float8</literal>
    can.  Also, the names <literal>interval</>, <literal>time</>, and
    <literal>timestamp</> can only be used in this fashion if they are
T
Tom Lane 已提交
1404
    double-quoted, because of syntactic conflicts.  Therefore, the use of
1405 1406
    the function-like cast syntax leads to inconsistencies and should
    probably be avoided in new applications.
1407 1408 1409 1410 1411

    (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
T
Tom Lane 已提交
1412 1413 1414 1415
    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.)
1416 1417 1418
   </para>
  </sect2>

1419
  <sect2 id="sql-syntax-scalar-subqueries">
1420 1421
   <title>Scalar Subqueries</title>

P
Peter Eisentraut 已提交
1422 1423 1424 1425
   <indexterm>
    <primary>subquery</primary>
   </indexterm>

1426 1427
   <para>
    A scalar subquery is an ordinary
1428 1429 1430
    <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
1431 1432 1433 1434
    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,
P
Peter Eisentraut 已提交
1435
    there is no error; the scalar result is taken to be null.)
1436 1437
    The subquery can refer to variables from the surrounding query,
    which will act as constants during any one evaluation of the subquery.
P
Peter Eisentraut 已提交
1438
    See also <xref linkend="functions-subquery"> for other expressions involving subqueries.
1439 1440 1441 1442 1443 1444 1445
   </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)
1446
    FROM states;
1447 1448 1449
</programlisting>
   </para>
  </sect2>
1450

1451 1452 1453
  <sect2 id="sql-syntax-array-constructors">
   <title>Array Constructors</title>

P
Peter Eisentraut 已提交
1454 1455 1456 1457
   <indexterm>
    <primary>array</primary>
    <secondary>constructor</secondary>
   </indexterm>
1458

1459 1460 1461 1462
   <indexterm>
    <primary>ARRAY</primary>
   </indexterm>

1463
   <para>
P
Peter Eisentraut 已提交
1464
    An array constructor is an expression that builds an
1465 1466
    array value from values for its member elements.  A simple array
    constructor 
1467
    consists of the key word <literal>ARRAY</literal>, a left square bracket
1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
    <literal>[</>, one or more expressions (separated by commas) for the
    array element values, and finally a right square bracket <literal>]</>.
    For example,
<programlisting>
SELECT ARRAY[1,2,3+4];
  array
---------
 {1,2,7}
(1 row)
</programlisting>
    The array element type is the common type of the member expressions,
    determined using the same rules as for <literal>UNION</> or
    <literal>CASE</> constructs (see <xref linkend="typeconv-union-case">). 
   </para>

   <para>
    Multidimensional array values can be built by nesting array
    constructors.
1486
    In the inner constructors, the key word <literal>ARRAY</literal> may
1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506
    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.
  </para>

1507 1508 1509 1510 1511
  <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>
P
Peter Eisentraut 已提交
1512 1513 1514 1515 1516
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;
1517 1518 1519 1520 1521 1522 1523
                     array
------------------------------------------------
 {{{1,2},{3,4}},{{5,6},{7,8}},{{9,10},{11,12}}}
(1 row)
</programlisting>
  </para>

1524 1525 1526
  <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
1527
   key word <literal>ARRAY</literal> followed by a parenthesized (not
1528 1529 1530 1531 1532 1533 1534 1535
   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>
P
Peter Eisentraut 已提交
1536 1537 1538 1539
   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.
1540 1541 1542 1543 1544 1545 1546 1547 1548 1549
  </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>

1550 1551 1552 1553
  <sect2 id="sql-syntax-row-constructors">
   <title>Row Constructors</title>

   <indexterm>
1554 1555 1556 1557 1558 1559
    <primary>composite type</primary>
    <secondary>constructor</secondary>
   </indexterm>

   <indexterm>
    <primary>row type</primary>
1560 1561 1562
    <secondary>constructor</secondary>
   </indexterm>

1563 1564 1565 1566
   <indexterm>
    <primary>ROW</primary>
   </indexterm>

1567
   <para>
1568 1569
    A row constructor is an expression that builds a row value (also
    called a composite value) from values
1570
    for its member fields.  A row constructor consists of the key word
1571
    <literal>ROW</literal>, a left parenthesis, zero or more
1572
    expressions (separated by commas) for the row field values, and finally
1573
    a right parenthesis.  For example,
1574
<programlisting>
1575
SELECT ROW(1,2.5,'this is a test');
1576 1577 1578 1579 1580
</programlisting>
    The key word <literal>ROW</> is optional when there is more than one
    expression in the list.
   </para>

1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605
   <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>

1606 1607 1608
   <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
P
Peter Eisentraut 已提交
1609
    composite type &mdash; either the row type of a table, or a composite type
1610 1611 1612 1613
    created with <command>CREATE TYPE AS</>.  An explicit cast may be needed
    to avoid ambiguity.  For example:
<programlisting>
CREATE TABLE mytable(f1 int, f2 float, f3 text);
1614

1615
CREATE FUNCTION getf1(mytable) RETURNS int AS 'SELECT $1.f1' LANGUAGE SQL;
1616

1617 1618 1619 1620 1621 1622 1623 1624
-- 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);
1625

1626
CREATE FUNCTION getf1(myrowtype) RETURNS int AS 'SELECT $1.f1' LANGUAGE SQL;
1627

1628 1629 1630
-- 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
1631

1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646
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>
1647 1648 1649 1650
   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
1651 1652 1653
   <literal>IS NULL</> or <literal>IS NOT NULL</>, for example
<programlisting>
SELECT ROW(1,2.5,'this is a test') = ROW(1, 3, 'not the same');
1654

1655
SELECT ROW(table.*) IS NULL FROM table;  -- detect all-null rows
1656 1657 1658 1659 1660 1661 1662 1663
</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>

1664
  <sect2 id="syntax-express-eval">
1665
   <title>Expression Evaluation Rules</title>
1666

P
Peter Eisentraut 已提交
1667 1668 1669 1670 1671
   <indexterm>
    <primary>expression</primary>
    <secondary>order of evaluation</secondary>
   </indexterm>

1672 1673
   <para>
    The order of evaluation of subexpressions is not defined.  In
1674 1675
    particular, the inputs of an operator or function are not necessarily
    evaluated left-to-right or in any other fixed order.
1676
   </para>
1677

1678
   <para>
1679
    Furthermore, if the result of an expression can be determined by
1680
    evaluating only some parts of it, then other subexpressions
1681
    might not be evaluated at all.  For instance, if one wrote
1682
<programlisting>
1683
SELECT true OR somefunc();
1684
</programlisting>
1685 1686
    then <literal>somefunc()</literal> would (probably) not be called
    at all. The same would be the case if one wrote
1687
<programlisting>
1688
SELECT somefunc() OR true;
1689
</programlisting>
1690 1691 1692
    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.
1693 1694 1695
   </para>

   <para>
1696
    As a consequence, it is unwise to use functions with side effects
1697
    as part of complex expressions.  It is particularly dangerous to
1698
    rely on side effects or evaluation order in <literal>WHERE</> and <literal>HAVING</> clauses,
1699 1700
    since those clauses are extensively reprocessed as part of
    developing an execution plan.  Boolean
1701
    expressions (<literal>AND</>/<literal>OR</>/<literal>NOT</> combinations) in those clauses may be reorganized
1702 1703 1704 1705
    in any manner allowed by the laws of Boolean algebra.
   </para>

   <para>
1706 1707 1708 1709
    When it is essential to force evaluation order, a <literal>CASE</>
    construct (see <xref linkend="functions-conditional">) may be
    used.  For example, this is an untrustworthy way of trying to
    avoid division by zero in a <literal>WHERE</> clause:
1710
<programlisting>
T
Tom Lane 已提交
1711
SELECT ... WHERE x &lt;&gt; 0 AND y/x &gt; 1.5;
1712
</programlisting>
1713
    But this is safe:
1714
<programlisting>
T
Tom Lane 已提交
1715
SELECT ... WHERE CASE WHEN x &lt;&gt; 0 THEN y/x &gt; 1.5 ELSE false END;
1716
</programlisting>
T
Tom Lane 已提交
1717 1718 1719 1720
    A <literal>CASE</> construct used in this fashion will defeat optimization
    attempts, so it should only be done when necessary.  (In this particular
    example, it would doubtless be best to sidestep the problem by writing
    <literal>y &gt; 1.5*x</> instead.)
1721
   </para>
1722 1723
  </sect2>
 </sect1>
1724 1725

</chapter>