syntax.sgml 38.8 KB
Newer Older
1
<!--
2
$Header: /cvsroot/pgsql/doc/src/sgml/syntax.sgml,v 1.45 2001/08/26 21:17:12 tgl Exp $
3 4
-->

5 6
<chapter id="sql-syntax">
 <title>SQL Syntax</title>
7

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

13 14
  <abstract>
   <para>
15
    A description of the general syntax of SQL.
16 17 18
   </para>
  </abstract>

19 20 21
 <sect1 id="sql-syntax-lexical">
  <title>Lexical Structure</title>

22
  <para>
23 24
   SQL input consists of a sequence of
   <firstterm>commands</firstterm>.  A command is composed of a
25 26 27 28
   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.
29 30
  </para>

31 32 33 34 35 36 37 38 39
  <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>
40

41 42 43 44 45 46 47
  <para>
   Additionally, <firstterm>comments</firstterm> can occur in SQL
   input.  They are not tokens, they are effectively equivalent to
   whitespace.
  </para>

  <informalexample id="sql-syntax-ex-commands">
48
   <para>
49
    For example, the following is (syntactically) valid SQL input:
50 51 52 53 54 55 56
<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
57
    commands can usefully be split across lines).
58
   </para>
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
  </informalexample>

  <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
   precise syntax rules for each command are described in the
   <citetitle>Reference Manual</citetitle>.
  </para>

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

78 79 80 81 82 83 84 85 86
   <indexterm zone="sql-syntax-identifiers">
    <primary>identifiers</primary>
   </indexterm>

   <indexterm zone="sql-syntax-identifiers">
    <primary>key words</primary>
    <secondary>syntax</secondary>
   </indexterm>

87
   <para>
88 89 90 91 92 93 94 95 96 97 98 99 100
    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">.
101 102 103
   </para>

   <para>
104 105 106 107 108 109
    SQL identifiers and key words must begin with a letter
    (<literal>a</literal>-<literal>z</literal>) or underscore
    (<literal>_</literal>).  Subsequent characters in an identifier or
    key word can be letters, digits
    (<literal>0</literal>-<literal>9</literal>), or underscores,
    although the SQL standard will not define a key word that contains
110
    digits or starts or ends with an underscore.
111 112
   </para>

113
   <para>
114 115 116 117 118 119 120
    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,
    <symbol>NAMEDATALEN</symbol> is 32 so the maximum identifier length
    is 31 (but at the time the system is built,
    <symbol>NAMEDATALEN</symbol> can be changed in
    <filename>src/include/postgres_ext.h</filename>).
121
   </para>
122

123
   <para>
124 125 126 127
    <indexterm>
     <primary>case sensitivity</primary>
     <secondary>SQL commands</secondary>
    </indexterm>
128 129 130 131 132 133 134 135
    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>
136
    A convention often used is to write key words in upper
137 138 139 140
    case and names in lower case, e.g.,
<programlisting>
UPDATE my_table SET a = 5;
</programlisting>
141 142 143
   </para>

   <para>
144 145 146 147
    <indexterm>
     <primary>quotes</primary>
     <secondary>and identifiers</secondary>
    </indexterm>
148 149 150 151 152 153 154 155
    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
156
    <literal>select</literal> would be taken as a key word and
157 158
    would therefore provoke a parse error when used where a table or
    column name is expected.  The example can be written with quoted
159
    identifiers like this:
160 161 162
<programlisting>
UPDATE "my_table" SET "a" = 5;
</programlisting>
163 164 165
   </para>

   <para>
166 167 168 169
    Quoted identifiers can contain any character other than a double
    quote itself.  This allows constructing table or column names that
    would otherwise not be possible, such as ones containing spaces or
    ampersands.  The length limitation still applies.
170
   </para>
171 172

   <para>
173 174 175 176 177 178 179 180 181
    Quoting an identifier also makes it case-sensitive, whereas
    unquoted names are always folded to lower case.  For example, the
    identifiers <literal>FOO</literal>, <literal>foo</literal> and
    <literal>"foo"</literal> are considered the same by
    <productname>Postgres</productname>, but <literal>"Foo"</literal>
    and <literal>"FOO"</literal> are different from these three and
    each other.
    <footnote>
     <para>
182 183 184 185 186 187 188
      <productname>Postgres</productname>' folding of unquoted names to lower
      case 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 particular
      name or never quote it.
189 190
     </para>
    </footnote>
191
   </para>
192 193
  </sect2>

194

195
  <sect2 id="sql-syntax-constants">
196 197
   <title>Constants</title>

198 199 200 201
   <indexterm zone="sql-syntax-constants">
    <primary>constants</primary>
   </indexterm>

202
   <para>
203 204 205 206 207 208
    There are four kinds of <firstterm>implicitly typed
    constants</firstterm> in <productname>Postgres</productname>:
    strings, bit strings, integers, and floating point numbers.
    Constants can also be specified with explicit types, which can
    enable more accurate representation and more efficient handling by
    the system. The implicit constants are described below; explicit
209
    constants are discussed afterwards.
210 211
   </para>

212
   <sect3 id="sql-syntax-strings">
213 214
    <title>String Constants</title>

215 216 217 218 219
    <indexterm zone="sql-syntax-strings">
     <primary>character strings</primary>
     <secondary>constants</secondary>
    </indexterm>

220
    <para>
221 222 223 224
     <indexterm>
      <primary>quotes</primary>
      <secondary>escaping</secondary>
     </indexterm>
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
     A string constant in SQL is an arbitrary sequence of characters
     bounded by single quotes (<quote>'</quote>), e.g., <literal>'This
     is a string'</literal>.  SQL allows single quotes to be embedded
     in strings by typing two adjacent single quotes (e.g.,
     <literal>'Dianne''s horse'</literal>).  In
     <productname>Postgres</productname> single quotes may
     alternatively be escaped with a backslash (<quote>\</quote>,
     e.g., <literal>'Dianne\'s horse'</literal>).
    </para>

    <para>
     C-style backslash escapes are also 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, and <literal>\<replaceable>xxx</replaceable></literal>,
     where <replaceable>xxx</replaceable> is an octal number, is the
     character with the corresponding ASCII code.  Any other character
     following a backslash is taken literally.  Thus, to include a
244
     backslash in a string constant, type two backslashes.
245 246
    </para>

247 248 249
    <para>
     The character with the code zero cannot be in a string constant.
    </para>
250

251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
    <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>
     is not valid syntax.
    </para>
   </sect3>

272
   <sect3 id="sql-syntax-bit-strings">
273
    <title>Bit String Constants</title>
274

275 276 277 278 279
    <indexterm zone="sql-syntax-bit-strings">
     <primary>bit strings</primary>
     <secondary>constants</secondary>
    </indexterm>

280
    <para>
281 282 283 284 285
     Bit string constants look like string constants with a
     <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
     bit string constants are <literal>0</literal> and
286
     <literal>1</literal>.  Bit string constants can be continued
287
     across lines in the same way as regular string constants.
288
    </para>
289
   </sect3>
290

291 292
   <sect3>
    <title>Integer Constants</title>
293 294

    <para>
295 296 297 298 299 300 301 302
     Integer constants in SQL are sequences of decimal digits (0
     though 9) with no decimal point.  The range of legal values
     depends on which integer data type is used, but the plain
     <type>integer</type> type accepts values ranging from -2147483648
     to +2147483647.  (The optional plus or minus sign is actually a
     separate unary operator and not part of the integer constant.)
    </para>
   </sect3>
303

304 305
   <sect3>
    <title>Floating Point Constants</title>
306

307 308 309 310 311
    <indexterm>
     <primary>floating point</primary>
     <secondary>constants</secondary>
    </indexterm>

312 313 314 315 316 317 318 319 320
    <para>
     Floating point constants are accepted in these general forms:
<synopsis>
<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
     digits.  At least one digit must be before or after the decimal
321
     point, and after the <literal>e</literal> if you use that option.
322 323 324 325
     Thus, a floating point constant is distinguished from an integer
     constant by the presence of either the decimal point or the
     exponent clause (or both).  There must not be a space or other
     characters embedded in the constant.
326 327
    </para>

328 329 330 331 332 333 334 335 336 337 338 339 340
    <informalexample>
     <para>
      These are some examples of valid floating point constants:
<literallayout>
3.5
4.
.001
5e2
1.925e-3
</literallayout>
     </para>
    </informalexample>

341
    <para>
342 343 344
     Floating point constants are of type <type>DOUBLE
     PRECISION</type>. <type>REAL</type> can be specified explicitly
     by using <acronym>SQL</acronym> string notation or
345 346
     <productname>Postgres</productname> type notation:

347 348 349
<programlisting>
REAL '1.23'  -- string style
'1.23'::REAL -- Postgres (historical) style
350
     </programlisting>
351
    </para>
352
   </sect3>
353

354
   <sect3 id="sql-syntax-constants-generic">
355
    <title>Constants of Other Types</title>
356

357 358 359 360 361
    <indexterm>
     <primary>data types</primary>
     <secondary>constants</secondary>
    </indexterm>

362
    <para>
363 364 365
     A constant of an <emphasis>arbitrary</emphasis> type can be
     entered using any one of the following notations:
<synopsis>
366 367
<replaceable>type</replaceable> '<replaceable>string</replaceable>'
'<replaceable>string</replaceable>'::<replaceable>type</replaceable>
368
CAST ( '<replaceable>string</replaceable>' AS <replaceable>type</replaceable> )
369 370 371 372 373 374 375 376
</synopsis>
     The value inside the string is passed to the input conversion
     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
     constant must be (for example, when it is passed as an argument
     to a non-overloaded function), in which case it is automatically
     coerced.
377
    </para>
378 379 380 381

    <para>
     It is also possible to specify a type coercion using a function-like
     syntax:
382
<synopsis>
383
<replaceable>typename</replaceable> ( <replaceable>value</replaceable> )
384
</synopsis>
385 386 387 388 389 390 391
     although 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.)
    </para>

    <para>
392 393 394 395 396 397
     The <literal>::</literal>, <literal>CAST()</literal>, and
     function-call syntaxes can also be used to specify the type of
     arbitrary expressions, but the form
     <replaceable>type</replaceable>
     '<replaceable>string</replaceable>' can only be used to specify
     the type of a literal constant.
398
    </para>
399
   </sect3>
400

401
   <sect3>
402 403
    <title>Array constants</title>

404 405 406 407 408
    <indexterm>
     <primary>arrays</primary>
     <secondary>constants</secondary>
    </indexterm>

409
    <para>
410
     The general format of an array constant is the following:
411 412 413 414 415 416 417 418 419 420 421 422
<synopsis>
'{ <replaceable>val1</replaceable> <replaceable>delim</replaceable> <replaceable>val2</replaceable> <replaceable>delim</replaceable> ... }'
</synopsis>
     where <replaceable>delim</replaceable> is the delimiter character
     for the type, as recorded in its <literal>pg_type</literal>
     entry.  (For all built-in types, this is the comma character
     ",".)  Each <replaceable>val</replaceable> is either a constant
     of the array element type, or a sub-array.  An example of an
     array constant is
<programlisting>
'{{1,2,3},{4,5,6},{7,8,9}}'
</programlisting>
423 424 425 426 427
     This constant is a two-dimensional, 3 by 3 array consisting of three
     sub-arrays of integers.
    </para>

    <para>
428
     Individual array elements can be placed between double-quote
429 430 431
     marks (<literal>"</literal>) <!-- " --> to avoid ambiguity
     problems with respect to white space.  Without quote marks, the
     array-value parser will skip leading white space.
432 433
    </para>

434 435 436 437 438 439 440 441 442 443 444 445 446 447
    <para>
     (Array constants are actually only a special case of the generic
     type constants discussed in the previous section.  The constant
     is initially treated as a string and passed to the array input
     conversion routine.  An explicit type specification might be
     necessary.)
    </para>
   </sect3>
  </sect2>


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

448 449 450 451 452
   <indexterm zone="sql-syntax-operators">
    <primary>operators</primary>
    <secondary>syntax</secondary>
   </indexterm>

453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
   <para>
    An operator is a sequence of up to <symbol>NAMEDATALEN</symbol>-1
    (31 by default) characters from the following list:
<literallayout>
+ - * / &lt; &gt; = ~ ! @ # % ^ &amp; | ` ? $
</literallayout>

    There are a few restrictions on operator names, however:
    <itemizedlist>
     <listitem>
      <para>
       "$" (dollar) cannot be a single-character operator, although it
       can be part of a multi-character operator name.
      </para>
     </listitem>

     <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>
       A multi-character operator name cannot end in "+" or "-",
       unless the name also contains at least one of these characters:
<literallayout>
~ ! @ # % ^ &amp; | ` ? $
</literallayout>
       For example, <literal>@-</literal> is an allowed operator name,
       but <literal>*-</literal> is not.  This restriction allows
       <productname>Postgres</productname> to parse SQL-compliant
       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.
    For example, if you have defined a left-unary operator named "@",
    you cannot write <literal>X*@Y</literal>; you must write
    <literal>X* @Y</literal> to ensure that
    <productname>Postgres</productname> reads it as two operator names
    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
      to represent the positional parameters in the body of a function
      definition.  In other contexts the dollar sign may be part of an
      operator name.
     </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.
551 552
      It cannot appear anywhere within a command, except within a
      string constant or quoted identifier.
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
     </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>
      The asterisk (<literal>*</literal>) has a special meaning when
      used in the <command>SELECT</command> command or with the
      <function>COUNT</function> aggregate function.
     </para>
    </listitem>

    <listitem>
     <para>
      The period (<literal>.</literal>) is used in floating point
      constants, and to separate table and column names.
     </para>
    </listitem>
   </itemizedlist>

   </para>
  </sect2>

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

587 588 589 590 591
   <indexterm zone="sql-syntax-comments">
    <primary>comments</primary>
    <secondary>in SQL</secondary>
   </indexterm>

592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
   <para>
    A comment is an arbitrary sequence of characters beginning with
    double dashes and extending to the end of the line, e.g.:
<programlisting>
-- This is a standard SQL92 comment
</programlisting>
   </para>

   <para>
    Alternatively, C-style block comments can be used:
<programlisting>
/* multi-line comment
 * with nesting: /* nested block comment */
 */
</programlisting>
    where the comment begins with <literal>/*</literal> and extends to
    the matching occurrence of <literal>*/</literal>. These block
    comments nest, as specified in SQL99 but unlike C, so that one can
    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>
 </sect1>


  <sect1 id="sql-syntax-columns">
623
   <title>Columns</title>
624 625

    <para>
626 627 628
     A <firstterm>column</firstterm>
     is either a user-defined column of a given table or one of the
     following system-defined columns:
629

630 631 632 633 634
     <indexterm>
      <primary>columns</primary>
      <secondary>system columns</secondary>
     </indexterm>

635 636 637 638 639
     <variablelist>
      <varlistentry>
       <term>oid</term>
       <listitem>
	<para>
640 641 642
	 <indexterm>
	  <primary>OID</primary>
	 </indexterm>
643
	 The object identifier (object ID) of a row.  This is a serial number
644 645 646
	 that is automatically added by Postgres to all table rows (unless
	 the table was created WITHOUT OIDS, in which case this column is
	 not present).
647 648 649 650 651
	</para>
       </listitem>
      </varlistentry>

      <varlistentry>
652
      <term>tableoid</term>
653 654
       <listitem>
	<para>
655 656 657 658 659
	 The OID of the table containing this row.  This attribute is
	 particularly handy for queries that select from inheritance
	 hierarchies, since without it, it's difficult to tell which
	 individual table a row came from.  The tableoid can be joined
	 against the OID attribute of pg_class to obtain the table name.
660 661 662 663 664
	</para>
       </listitem>
      </varlistentry>

      <varlistentry>
665
       <term>xmin</term>
666 667
       <listitem>
	<para>
668 669 670
	 The identity (transaction ID) of the inserting transaction for
	 this tuple.  (Note: a tuple is an individual state of a row;
	 each UPDATE of a row creates a new tuple for the same logical row.)
671 672 673 674 675 676 677 678
	</para>
       </listitem>
      </varlistentry>

      <varlistentry>
      <term>cmin</term>
       <listitem>
	<para>
679 680 681 682 683 684 685 686 687 688 689
	 The command identifier (starting at zero) within the inserting
	 transaction.
	</para>
       </listitem>
      </varlistentry>

      <varlistentry>
      <term>xmax</term>
       <listitem>
	<para>
	 The identity (transaction ID) of the deleting transaction,
690
	 or zero for an undeleted tuple.  It is possible for this field
691
	 to be nonzero in a visible tuple: that usually indicates that the
692 693
	 deleting transaction hasn't committed yet, or that an attempted
	 deletion was rolled back.
694 695 696 697 698 699 700 701
	</para>
       </listitem>
      </varlistentry>

      <varlistentry>
      <term>cmax</term>
       <listitem>
	<para>
702 703 704 705 706 707 708 709 710 711 712 713 714
	 The command identifier within the deleting transaction, or zero.
	</para>
       </listitem>
      </varlistentry>

      <varlistentry>
      <term>ctid</term>
       <listitem>
	<para>
	 The tuple ID of the tuple within its table.  This is a pair
	 (block number, tuple index within block) that identifies the
	 physical location of the tuple.  Note that although the ctid
	 can be used to locate the tuple very quickly, a row's ctid
715 716
	 will change each time it is updated or moved by <command>VACUUM
	 FULL</>.
717 718 719
	 Therefore ctid is useless as a long-term row identifier.
	 The OID, or even better a user-defined serial number, should
	 be used to identify logical rows.
720 721 722 723 724 725
	</para>
       </listitem>
      </varlistentry>
     </variablelist>
    </para>

726 727 728 729 730 731 732 733 734 735 736 737 738 739 740
    <para>
     OIDs are 32-bit quantities and are assigned from a single cluster-wide
     counter.  In a large or long-lived database, it is possible for the
     counter to wrap around.  Hence, it is bad practice to assume that OIDs
     are unique, unless you take steps to ensure that they are unique.
     Recommended practice when using OIDs for row identification is to create
     a unique index on the OID column of each table for which the OID will be
     used.  Never assume that OIDs are unique across tables; use the
     combination of tableoid and row OID if you need a database-wide
     identifier.  (Future releases of Postgres are likely to use a separate
     OID counter for each table, so that tableoid <emphasis>must</> be
     included to arrive at a globally unique identifier.)
    </para>

    <para>
741 742 743 744 745 746 747 748 749 750 751 752 753
     Transaction identifiers are 32-bit quantities.  In a long-lived
     database it is possible for transaction IDs to wrap around.  This
     is not a fatal problem given appropriate maintenance procedures;
     see the Administrator's Guide for details.  However, it is unwise
     to depend on uniqueness of transaction IDs over the long term
     (more than one billion transactions).
    </para>

    <para>
     Command identifiers are also 32-bit quantities.  This creates a hard
     limit of 2^32 (4 billion) SQL commands within a single transaction.
     In practice this limit is not a problem --- note that the limit is on
     number of SQL queries, not number of tuples processed.
754 755
    </para>

756
    <para>
757
     For further information on the system attributes consult
758 759 760
     <xref linkend="STON87a" endterm="STON87a">.
    </para>

761
  </sect1>
762

763

764 765
 <sect1 id="sql-expressions">
  <title>Value Expressions</title>
766

767
  <para>
768
   Value expressions are used in a variety of contexts, such
769 770 771 772 773 774 775 776 777 778 779
   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>
780

781 782
  <para>
   A value expression is one of the following:
783

784 785 786 787 788 789
   <itemizedlist>
    <listitem>
     <para>
      A constant or literal value; see <xref linkend="sql-syntax-constants">.
     </para>
    </listitem>
790

791 792 793 794 795
    <listitem>
     <para>
      A column reference
     </para>
    </listitem>
796

797 798 799 800 801 802
    <listitem>
     <para>
      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>
803
       <member><replaceable>expression</replaceable> <replaceable>operator</replaceable> (unary postfix operator)</member>
804 805 806 807
      </simplelist>
      where <replaceable>operator</replaceable> follows the syntax
      rules of <xref linkend="sql-syntax-operators"> or is one of the
      tokens <token>AND</token>, <token>OR</token>, and
808
      <token>NOT</token>.  Which particular operators exist and whether
809 810 811 812 813
      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>
    </listitem>
814

815 816 817 818 819 820
    <listitem>
     <para>
<synopsis>( <replaceable>expression</replaceable> )</synopsis>
      Parentheses are used to group subexpressions and override precedence.
     </para>
    </listitem>
821

822 823 824 825 826
    <listitem>
     <para>
      A positional parameter reference, in the body of a function declaration.
     </para>
    </listitem>
827

828 829 830 831 832
    <listitem>
     <para>
      A function call
     </para>
    </listitem>
833

834 835 836 837 838
    <listitem>
     <para>
      An aggregate expression
     </para>
    </listitem>
839

840 841 842
    <listitem>
     <para>
      A scalar subquery.  This is an ordinary
843
      <command>SELECT</command> in parentheses that returns exactly one
844 845 846 847 848 849 850
      row with one column.  It is an error to use a subquery that
      returns more than one row or more than one column in the context
      of a value expression.
     </para>
    </listitem>
   </itemizedlist>
  </para>
851

852
  <para>
853
   In addition to this list, there are a number of constructs that can
854 855 856 857 858 859
   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>
860

861 862 863 864 865
  <para>
   We have already discussed constants in <xref
   linkend="sql-syntax-constants">.  The following sections discuss
   the remaining options.
  </para>
866

867 868
  <sect2>
   <title>Column References</title>
869

870 871 872
   <para>
    A column can be referenced in the form:
<synopsis>
873
<replaceable>correlation</replaceable>.<replaceable>columnname</replaceable> `['<replaceable>subscript</replaceable>`]'
874
</synopsis>
875

876
    <replaceable>correlation</replaceable> is either the name of a
877 878 879
    table, an alias for a table defined by means of a FROM clause, or
    the keyword <literal>NEW</literal> or <literal>OLD</literal>.
    (NEW and OLD can only appear in the action portion of a rule,
880 881
    while other correlation names can be used in any SQL statement.)
    The correlation name can be omitted if the column name is unique
882 883 884 885 886 887 888 889 890
    across all the tables being used in the current query.  If
    <replaceable>column</replaceable> is of an array type, then the
    optional <replaceable>subscript</replaceable> selects a specific
    element in the array.  If no subscript is provided, then the whole
    array is selected.  Refer to the description of the particular
    commands in the <citetitle>PostgreSQL Reference Manual</citetitle>
    for the allowed syntax in each case.
   </para>
  </sect2>
891

892 893
  <sect2>
   <title>Positional Parameters</title>
894

895 896 897 898 899 900 901 902
   <para>
    A positional parameter reference is used to indicate a parameter
    in an SQL function.  Typically this is used in SQL function
    definition statements.  The form of a parameter is:
<synopsis>
$<replaceable>number</replaceable>
</synopsis>
   </para>
903

904 905 906
   <para>
    For example, consider the definition of a function,
    <function>dept</function>, as
907

908 909 910 911 912
<programlisting>
CREATE FUNCTION dept (text) RETURNS dept
  AS 'select * from dept where name = $1'
  LANGUAGE 'sql';
</programlisting>
913

914 915 916 917
    Here the <literal>$1</literal> will be replaced by the first
    function argument when the function is invoked.
   </para>
  </sect2>
918

919 920
  <sect2>
   <title>Function Calls</title>
921

922
   <para>
923 924 925
    The syntax for a function call is the name of a function
    (which is subject to the syntax rules for identifiers of <xref
    linkend="sql-syntax-identifiers">), followed by its argument list
926
    enclosed in parentheses:
927

928 929 930 931
<synopsis>
<replaceable>function</replaceable> (<optional><replaceable>expression</replaceable> <optional>, <replaceable>expression</replaceable> ... </optional></optional> )
</synopsis>
   </para>
932

933 934 935 936 937 938
   <para>
    For example, the following computes the square root of 2:
<programlisting>
sqrt(2)
</programlisting>
   </para>
939

940 941 942 943 944
   <para>
    The list of built-in functions is in <xref linkend="functions">.
    Other functions may be added by the user.
   </para>
  </sect2>
945

946 947
  <sect2 id="syntax-aggregates">
   <title>Aggregate Expressions</title>
948

949 950 951 952
   <indexterm zone="syntax-aggregates">
    <primary>aggregate functions</primary>
   </indexterm>

953 954 955 956 957 958
   <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:
959

960 961 962 963 964 965
    <simplelist>
     <member><replaceable>aggregate_name</replaceable> (<replaceable>expression</replaceable>)</member>
     <member><replaceable>aggregate_name</replaceable> (ALL <replaceable>expression</replaceable>)</member>
     <member><replaceable>aggregate_name</replaceable> (DISTINCT <replaceable>expression</replaceable>)</member>
     <member><replaceable>aggregate_name</replaceable> ( * )</member>
    </simplelist>
966

967 968 969 970 971
    where <replaceable>aggregate_name</replaceable> is a previously
    defined aggregate, and <replaceable>expression</replaceable> is
    any expression that does not itself contain an aggregate
    expression.
   </para>
972

973 974 975
   <para>
    The first form of aggregate expression invokes the aggregate
    across all input rows for which the given expression yields a
976 977 978
    non-NULL value.  (Actually, it is up to the aggregate function
    whether to ignore NULLs or not --- but all the standard ones do.)
    The second form is the same as the first, since
979 980 981 982 983 984 985
    <literal>ALL</literal> is the default.  The third form invokes the
    aggregate for all distinct non-NULL values of the expression found
    in the input rows.  The last form invokes the aggregate once for
    each input row regardless of NULL or non-NULL values; since no
    particular input value is specified, it is generally only useful
    for the <function>count()</function> aggregate function.
   </para>
986

987 988 989 990 991 992 993
   <para>
    For example, <literal>count(*)</literal> yields the total number
    of input rows; <literal>count(f1)</literal> yields the number of
    input rows in which <literal>f1</literal> is non-NULL;
    <literal>count(distinct f1)</literal> yields the number of
    distinct non-NULL values of <literal>f1</literal>.
   </para>
994

995 996
   <para>
    The predefined aggregate functions are described in <xref
997 998
    linkend="functions-aggregate">.  Other aggregate functions may be added
    by the user. 
999 1000
   </para>
  </sect2>
1001

1002
 </sect1>
1003 1004


1005
  <sect1 id="sql-precedence">
1006 1007
   <title>Lexical Precedence</title>

1008 1009 1010 1011 1012
   <indexterm zone="sql-precedence">
    <primary>operators</primary>
    <secondary>precedence</secondary>
   </indexterm>

1013 1014 1015 1016
   <para>
    The precedence and associativity of the operators is hard-wired
    into the parser.  Most operators have the same precedence and are
    left-associative.  This may lead to non-intuitive behavior; for
1017 1018
    example the Boolean operators "&lt;" and "&gt;" have a different
    precedence than the Boolean operators "&lt;=" and "&gt;=".  Also,
1019
    you will sometimes need to add parentheses when using combinations
1020 1021
    of binary and unary operators.  For instance
<programlisting>
1022
SELECT 5 ! - 6;
1023 1024 1025
</programlisting>
   will be parsed as
<programlisting>
1026
SELECT 5 ! (- 6);
1027
</programlisting>
1028 1029
    because the parser has no idea -- until it is too late -- that
    <token>!</token> is defined as a postfix operator, not an infix one.
1030 1031
    To get the desired behavior in this case, you must write
<programlisting>
1032
SELECT (5 !) - 6;
1033
</programlisting>
1034
    This is the price one pays for extensibility.
1035 1036 1037
   </para>

   <table tocentry="1">
1038
    <title>Operator Precedence (decreasing)</title>
1039 1040 1041 1042

    <tgroup cols="2">
     <thead>
      <row>
1043
       <entry>Operator/Element</entry>
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
       <entry>Associativity</entry>
       <entry>Description</entry>
      </row>
     </thead>

     <tbody>
      <row>
       <entry><token>::</token></entry>
       <entry>left</entry>
       <entry><productname>Postgres</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>left</entry>
       <entry>table/column name separator</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>
1095
       <entry>test for TRUE, FALSE, UNKNOWN, NULL</entry>
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 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 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
      </row>

      <row>
       <entry><token>ISNULL</token></entry>
       <entry></entry>
       <entry>test for NULL</entry>
      </row>

      <row>
       <entry><token>NOTNULL</token></entry>
       <entry></entry>
       <entry>test for NOT NULL</entry>
      </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>
       <entry>containment</entry>
      </row>

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

      <row>
       <entry><token>LIKE</token> <token>ILIKE</token></entry>
       <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
1175 1176
    operators that have the same names as the built-in operators
    mentioned above.  For example, if you define a
1177 1178 1179 1180
    <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>
1181 1182 1183
  </sect1>

</chapter>
1184 1185 1186

<!-- Keep this comment at the end of the file
Local variables:
1187
mode:sgml
1188 1189 1190 1191 1192 1193 1194 1195 1196
sgml-omittag:nil
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
sgml-parent-document:nil
sgml-default-dtd-file:"./reference.ced"
sgml-exposed-tags:nil
1197
sgml-local-catalogs:("/usr/lib/sgml/catalog")
1198 1199 1200
sgml-local-ecat-files:nil
End:
-->