select.sgml 42.1 KB
Newer Older
1
<!--
2
$PostgreSQL: pgsql/doc/src/sgml/ref/select.sgml,v 1.80 2005/01/04 08:59:45 tgl Exp $
3
PostgreSQL documentation
4 5
-->

6 7
<refentry id="SQL-SELECT">
 <refmeta>
8
  <refentrytitle id="sql-select-title">SELECT</refentrytitle>
9 10
  <refmiscinfo>SQL - Language Statements</refmiscinfo>
 </refmeta>
11

12
 <refnamediv>
13 14 15 16
  <refname>SELECT</refname>
  <refpurpose>retrieve rows from a table or view</refpurpose>
 </refnamediv>

Peter Eisentraut's avatar
Peter Eisentraut committed
17 18 19 20
 <indexterm zone="sql-select">
  <primary>SELECT</primary>
 </indexterm>

21
 <refsynopsisdiv>
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
<synopsis>
SELECT [ ALL | DISTINCT [ ON ( <replaceable class="parameter">expression</replaceable> [, ...] ) ] ]
    * | <replaceable class="parameter">expression</replaceable> [ AS <replaceable class="parameter">output_name</replaceable> ] [, ...]
    [ FROM <replaceable class="parameter">from_item</replaceable> [, ...] ]
    [ WHERE <replaceable class="parameter">condition</replaceable> ]
    [ GROUP BY <replaceable class="parameter">expression</replaceable> [, ...] ]
    [ HAVING <replaceable class="parameter">condition</replaceable> [, ...] ]
    [ { UNION | INTERSECT | EXCEPT } [ ALL ] <replaceable class="parameter">select</replaceable> ]
    [ ORDER BY <replaceable class="parameter">expression</replaceable> [ ASC | DESC | USING <replaceable class="parameter">operator</replaceable> ] [, ...] ]
    [ LIMIT { <replaceable class="parameter">count</replaceable> | ALL } ]
    [ OFFSET <replaceable class="parameter">start</replaceable> ]
    [ FOR UPDATE [ OF <replaceable class="parameter">table_name</replaceable> [, ...] ] ]

where <replaceable class="parameter">from_item</replaceable> can be one of:

    [ ONLY ] <replaceable class="parameter">table_name</replaceable> [ * ] [ [ AS ] <replaceable class="parameter">alias</replaceable> [ ( <replaceable class="parameter">column_alias</replaceable> [, ...] ) ] ]
    ( <replaceable class="parameter">select</replaceable> ) [ AS ] <replaceable class="parameter">alias</replaceable> [ ( <replaceable class="parameter">column_alias</replaceable> [, ...] ) ]
    <replaceable class="parameter">function_name</replaceable> ( [ <replaceable class="parameter">argument</replaceable> [, ...] ] ) [ AS ] <replaceable class="parameter">alias</replaceable> [ ( <replaceable class="parameter">column_alias</replaceable> [, ...] | <replaceable class="parameter">column_definition</replaceable> [, ...] ) ]
    <replaceable class="parameter">function_name</replaceable> ( [ <replaceable class="parameter">argument</replaceable> [, ...] ] ) AS ( <replaceable class="parameter">column_definition</replaceable> [, ...] )
    <replaceable class="parameter">from_item</replaceable> [ NATURAL ] <replaceable class="parameter">join_type</replaceable> <replaceable class="parameter">from_item</replaceable> [ ON <replaceable class="parameter">join_condition</replaceable> | USING ( <replaceable class="parameter">join_column</replaceable> [, ...] ) ]
</synopsis>

 </refsynopsisdiv>

 <refsect1>
  <title>Description</title>

  <para>
   <command>SELECT</command> retrieves rows from one or more tables.
   The general processing of <command>SELECT</command> is as follows:

   <orderedlist>
    <listitem>
     <para>
      All elements in the <literal>FROM</literal> list are computed.
      (Each element in the <literal>FROM</literal> list is a real or
      virtual table.)  If more than one element is specified in the
      <literal>FROM</literal> list, they are cross-joined together.
      (See <xref linkend="sql-from" endterm="sql-from-title"> below.)
     </para>
    </listitem>

    <listitem>
     <para>
      If the <literal>WHERE</literal> clause is specified, all rows
      that do not satisfy the condition are eliminated from the
      output.  (See <xref linkend="sql-where"
      endterm="sql-where-title"> below.)
     </para>
    </listitem>

    <listitem>
     <para>
      If the <literal>GROUP BY</literal> clause is specified, the
      output is divided into groups of rows that match on one or more
      values.  If the <literal>HAVING</literal> clause is present, it
      eliminates groups that do not satisfy the given condition.  (See
      <xref linkend="sql-groupby" endterm="sql-groupby-title"> and
      <xref linkend="sql-having" endterm="sql-having-title"> below.)
     </para>
    </listitem>

84 85 86 87 88 89 90 91 92 93
    <listitem>
     <para>
      The actual output rows are computed using the
      <command>SELECT</command> output expressions for each selected
      row.  (See
      <xref linkend="sql-select-list" endterm="sql-select-list-title">
      below.)
     </para>
    </listitem>

94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
    <listitem>
     <para>
      Using the operators <literal>UNION</literal>,
      <literal>INTERSECT</literal>, and <literal>EXCEPT</literal>, the
      output of more than one <command>SELECT</command> statement can
      be combined to form a single result set.  The
      <literal>UNION</literal> operator returns all rows that are in
      one or both of the result sets.  The
      <literal>INTERSECT</literal> operator returns all rows that are
      strictly in both result sets.  The <literal>EXCEPT</literal>
      operator returns the rows that are in the first result set but
      not in the second.  In all three cases, duplicate rows are
      eliminated unless <literal>ALL</literal> is specified. (See
      <xref linkend="sql-union" endterm="sql-union-title">, <xref
      linkend="sql-intersect" endterm="sql-intersect-title">, and
      <xref linkend="sql-except" endterm="sql-except-title"> below.)
     </para>
    </listitem>

    <listitem>
     <para>
      If the <literal>ORDER BY</literal> clause is specified, the
      returned rows are sorted in the specified order.  If
      <literal>ORDER BY</literal> is not given, the rows are returned
      in whatever order the system finds fastest to produce.  (See
      <xref linkend="sql-orderby" endterm="sql-orderby-title"> below.)
     </para>
    </listitem>

    <listitem>
     <para>
      <literal>DISTINCT</literal> eliminates duplicate rows from the
      result.  <literal>DISTINCT ON</literal> eliminates rows that
      match on all the specified expressions.  <literal>ALL</literal>
      (the default) will return all candidate rows, including
      duplicates.  (See <xref linkend="sql-distinct"
      endterm="sql-distinct-title"> below.)
     </para>
    </listitem>

Tom Lane's avatar
Tom Lane committed
134 135 136 137 138 139 140 141 142
    <listitem>
     <para>
      If the <literal>LIMIT</literal> or <literal>OFFSET</literal>
      clause is specified, the <command>SELECT</command> statement
      only returns a subset of the result rows. (See <xref
      linkend="sql-limit" endterm="sql-limit-title"> below.)
     </para>
    </listitem>

143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
    <listitem>
     <para>
      The <literal>FOR UPDATE</literal> clause causes the
      <command>SELECT</command> statement to lock the selected rows
      against concurrent updates.  (See <xref linkend="sql-for-update"
      endterm="sql-for-update-title"> below.)
     </para>
    </listitem>
   </orderedlist>
  </para>
   
  <para>
   You must have <literal>SELECT</literal> privilege on a table to
   read its values.  The use of <literal>FOR UPDATE</literal> requires
   <literal>UPDATE</literal> privilege as well.
  </para>
 </refsect1>

 <refsect1>
  <title>Parameters</title>

  <refsect2 id="SQL-FROM">
   <title id="sql-from-title"><literal>FROM</literal> Clause</title>
166

167
   <para>
168 169 170 171 172 173 174 175 176
    The <literal>FROM</literal> clause specifies one or more source
    tables for the <command>SELECT</command>.  If multiple sources are
    specified, the result is the Cartesian product (cross join) of all
    the sources.  But usually qualification conditions
    are added to restrict the returned rows to a small subset of the
    Cartesian product.
   </para>

   <para>
177 178
    The <literal>FROM</literal> clause can contain the following
    elements:
179

180 181
    <variablelist>
     <varlistentry>
182
      <term><replaceable class="parameter">table_name</replaceable></term>
183 184
      <listitem>
       <para>
185 186 187 188 189 190 191 192
        The name (optionally schema-qualified) of an existing table or
        view.  If <literal>ONLY</> is specified, only that table is
        scanned.  If <literal>ONLY</> is not specified, the table and
        all its descendant tables (if any) are scanned.  <literal>*</>
        can be appended to the table name to indicate that descendant
        tables are to be scanned, but in the current version, this is
        the default behavior.  (In releases before 7.1,
        <literal>ONLY</> was the default behavior.)  The default
193 194
        behavior can be modified by changing the <xref
        linkend="guc-sql-inheritance"> configuration option.
195 196 197 198 199
       </para>
      </listitem>
     </varlistentry>
     
     <varlistentry>
200
      <term><replaceable class="parameter">alias</replaceable></term>
201 202
      <listitem>
       <para>
203 204 205 206 207 208 209 210 211 212
        A substitute name for the <literal>FROM</> item containing the
        alias.  An alias is used for brevity or to eliminate ambiguity
        for self-joins (where the same table is scanned multiple
        times).  When an alias is provided, it completely hides the
        actual name of the table or function; for example given
        <literal>FROM foo AS f</>, the remainder of the
        <command>SELECT</command> must refer to this <literal>FROM</>
        item as <literal>f</> not <literal>foo</>.  If an alias is
        written, a column alias list can also be written to provide
        substitute names for one or more columns of the table.
213 214 215 216 217
       </para>
      </listitem>
     </varlistentry>
     
     <varlistentry>
218
      <term><replaceable class="parameter">select</replaceable></term>
219 220
      <listitem>
       <para>
221 222 223 224 225 226 227
        A sub-<command>SELECT</command> can appear in the
        <literal>FROM</literal> clause.  This acts as though its
        output were created as a temporary table for the duration of
        this single <command>SELECT</command> command.  Note that the
        sub-<command>SELECT</command> must be surrounded by
        parentheses, and an alias <emphasis>must</emphasis> be
        provided for it.
228 229 230
       </para>
      </listitem>
     </varlistentry>
231

232
     <varlistentry>
233
      <term><replaceable class="parameter">function_name</replaceable></term>
234 235
      <listitem>
       <para>
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
        Function calls can appear in the <literal>FROM</literal>
        clause.  (This is especially useful for functions that return
        result sets, but any function can be used.)  This acts as
        though its output were created as a temporary table for the
        duration of this single <command>SELECT</command> command. An
        alias may also be used. If an alias is written, a column alias
        list can also be written to provide substitute names for one
        or more attributes of the function's composite return type. If
        the function has been defined as returning the <type>record</>
        data type, then an alias or the key word <literal>AS</> must
        be present, followed by a column definition list in the form
        <literal>( <replaceable
        class="parameter">column_name</replaceable> <replaceable
        class="parameter">data_type</replaceable> <optional>, ... </>
        )</literal>.  The column definition list must match the actual
        number and types of columns returned by the function.
252 253 254 255 256
       </para>
      </listitem>
     </varlistentry>
     
     <varlistentry>
257
      <term><replaceable class="parameter">join_type</replaceable></term>
258 259
      <listitem>
       <para>
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
        One of
        <itemizedlist>
         <listitem>
          <para><literal>[ INNER ] JOIN</literal></para>
         </listitem>
         <listitem>
          <para><literal>LEFT [ OUTER ] JOIN</literal></para>
         </listitem>
         <listitem>
          <para><literal>RIGHT [ OUTER ] JOIN</literal></para>
         </listitem>
         <listitem>
          <para><literal>FULL [ OUTER ] JOIN</literal></para>
         </listitem>
         <listitem>
          <para><literal>CROSS JOIN</literal></para>
         </listitem>
        </itemizedlist>

        For the <literal>INNER</> and <literal>OUTER</> join types, a
        join condition must be specified, namely exactly one of
        <literal>NATURAL</>, <literal>ON <replaceable
        class="parameter">join_condition</replaceable></literal>, or
        <literal>USING (<replaceable
        class="parameter">join_column</replaceable> [, ...])</literal>.
        See below for the meaning.  For <literal>CROSS JOIN</literal>,
        none of these clauses may appear.
287
       </para>
288

289
       <para>
Tom Lane's avatar
Tom Lane committed
290 291 292
        A <literal>JOIN</literal> clause combines two
        <literal>FROM</> items.  Use parentheses if necessary to
        determine the order of nesting.  In the absence of parentheses,
293 294 295
        <literal>JOIN</literal>s nest left-to-right.  In any case
        <literal>JOIN</literal> binds more tightly than the commas
        separating <literal>FROM</> items.
296
       </para>
297

298
       <para>
299
        <literal>CROSS JOIN</> and <literal>INNER JOIN</literal>
Tom Lane's avatar
Tom Lane committed
300 301
        produce a simple Cartesian product, the same result as you get from
        listing the two items at the top level of <literal>FROM</>,
302
        but restricted by the join condition (if any).
303
        <literal>CROSS JOIN</> is equivalent to <literal>INNER JOIN ON
Tom Lane's avatar
Tom Lane committed
304
        (TRUE)</>, that is, no rows are removed by qualification.
305 306 307
        These join types are just a notational convenience, since they
        do nothing you couldn't do with plain <literal>FROM</> and
        <literal>WHERE</>.
308
       </para>
309

310
       <para>
311 312 313 314 315 316 317
        <literal>LEFT OUTER JOIN</> returns all rows in the qualified
        Cartesian product (i.e., all combined rows that pass its join
        condition), plus one copy of each row in the left-hand table
        for which there was no right-hand row that passed the join
        condition.  This left-hand row is extended to the full width
        of the joined table by inserting null values for the
        right-hand columns.  Note that only the <literal>JOIN</>
Tom Lane's avatar
Tom Lane committed
318
        clause's own condition is considered while deciding which rows
319
        have matches.  Outer conditions are applied afterwards.
320
       </para>
321 322

       <para>
323 324 325 326 327
        Conversely, <literal>RIGHT OUTER JOIN</> returns all the
        joined rows, plus one row for each unmatched right-hand row
        (extended with nulls on the left).  This is just a notational
        convenience, since you could convert it to a <literal>LEFT
        OUTER JOIN</> by switching the left and right inputs.
328
       </para>
329

330
       <para>
331 332 333 334
        <literal>FULL OUTER JOIN</> returns all the joined rows, plus
        one row for each unmatched left-hand row (extended with nulls
        on the right), plus one row for each unmatched right-hand row
        (extended with nulls on the left).
335 336 337 338 339
       </para>
      </listitem>
     </varlistentry>
     
     <varlistentry>
340
      <term><literal>ON <replaceable class="parameter">join_condition</replaceable></literal></term>
341 342
      <listitem>
       <para>
343 344 345 346 347
        <replaceable class="parameter">join_condition</replaceable> is
        an expression resulting in a value of type
        <type>boolean</type> (similar to a <literal>WHERE</literal>
        clause) that specifies which rows in a join are considered to
        match.
348 349 350 351
       </para>
      </listitem>
     </varlistentry>
     
352
     <varlistentry>
353
      <term><literal>USING (<replaceable class="parameter">join_column</replaceable> [, ...])</literal></term>
354 355
      <listitem>
       <para>
356 357 358 359 360 361
        A clause of the form <literal>USING ( a, b, ... )</literal> is
        shorthand for <literal>ON left_table.a = right_table.a AND
        left_table.b = right_table.b ...</literal>.  Also,
        <literal>USING</> implies that only one of each pair of
        equivalent columns will be included in the join output, not
        both.
362 363 364 365
       </para>
      </listitem>
     </varlistentry>

366
     <varlistentry>
367
      <term><literal>NATURAL</literal></term>
368 369
      <listitem>
       <para>
370 371 372
        <literal>NATURAL</literal> is shorthand for a
        <literal>USING</> list that mentions all columns in the two
        tables that have the same names.
373 374 375 376
       </para>
      </listitem>
     </varlistentry>
    </variablelist>
377
   </para>
378
  </refsect2>
379
   
380 381
  <refsect2 id="SQL-WHERE">
   <title id="sql-where-title"><literal>WHERE</literal> Clause</title>
382 383

   <para>
384 385 386 387 388 389 390 391 392 393
    The optional <literal>WHERE</literal> clause has the general form
<synopsis>
WHERE <replaceable class="parameter">condition</replaceable>
</synopsis>
    where <replaceable class="parameter">condition</replaceable> is
    any expression that evaluates to a result of type
    <type>boolean</type>.  Any row that does not satisfy this
    condition will be eliminated from the output.  A row satisfies the
    condition if it returns true when the actual row values are
    substituted for any variable references.
394
   </para>
395 396 397 398
  </refsect2>
  
  <refsect2 id="SQL-GROUPBY">
   <title id="sql-groupby-title"><literal>GROUP BY</literal> Clause</title>
399 400

   <para>
401 402 403 404
    The optional <literal>GROUP BY</literal> clause has the general form
<synopsis>
GROUP BY <replaceable class="parameter">expression</replaceable> [, ...]
</synopsis>
405 406 407
   </para>

   <para>
408 409 410 411 412
    <literal>GROUP BY</literal> will condense into a single row all
    selected rows that share the same values for the grouped
    expressions.  <replaceable
    class="parameter">expression</replaceable> can be an input column
    name, or the name or ordinal number of an output column
Tom Lane's avatar
Tom Lane committed
413
    (<command>SELECT</command> list item), or an arbitrary
414 415 416
    expression formed from input-column values.  In case of ambiguity,
    a <literal>GROUP BY</literal> name will be interpreted as an
    input-column name rather than an output column name.
417 418
   </para>

419
   <para>
420 421 422 423 424 425 426 427 428
    Aggregate functions, if any are used, are computed across all rows
    making up each group, producing a separate value for each group
    (whereas without <literal>GROUP BY</literal>, an aggregate
    produces a single value computed across all the selected rows).
    When <literal>GROUP BY</literal> is present, it is not valid for
    the <command>SELECT</command> list expressions to refer to
    ungrouped columns except within aggregate functions, since there
    would be more than one possible value to return for an ungrouped
    column.
429
   </para>
430
  </refsect2>
431

432 433
  <refsect2 id="SQL-HAVING">
   <title id="sql-having-title"><literal>HAVING</literal> Clause</title>
434

435
   <para>
436 437 438 439 440 441
    The optional <literal>HAVING</literal> clause has the general form
<synopsis>
HAVING <replaceable class="parameter">condition</replaceable>
</synopsis>
    where <replaceable class="parameter">condition</replaceable> is
    the same as specified for the <literal>WHERE</literal> clause.
442
   </para>
443
    
444
   <para>
445 446 447 448 449 450 451 452 453
    <literal>HAVING</literal> eliminates group rows that do not
    satisfy the condition.  <literal>HAVING</literal> is different
    from <literal>WHERE</literal>: <literal>WHERE</literal> filters
    individual rows before the application of <literal>GROUP
    BY</literal>, while <literal>HAVING</literal> filters group rows
    created by <literal>GROUP BY</literal>.  Each column referenced in
    <replaceable class="parameter">condition</replaceable> must
    unambiguously reference a grouping column, unless the reference
    appears within an aggregate function.
454
   </para>
455
  </refsect2>
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

  <refsect2 id="sql-select-list">
   <title id="sql-select-list-title"><command>SELECT</command> List</title>

   <para>
    The <command>SELECT</command> list (between the key words
    <literal>SELECT</> and <literal>FROM</>) specifies expressions
    that form the output rows of the <command>SELECT</command>
    statement.  The expressions can (and usually do) refer to columns
    computed in the <literal>FROM</> clause.  Using the clause
    <literal>AS <replaceable
    class="parameter">output_name</replaceable></literal>, another
    name can be specified for an output column.  This name is
    primarily used to label the column for display.  It can also be
    used to refer to the column's value in <literal>ORDER BY</> and
    <literal>GROUP BY</> clauses, but not in the <literal>WHERE</> or
    <literal>HAVING</> clauses; there you must write out the
    expression instead.
   </para>

   <para>
    Instead of an expression, <literal>*</literal> can be written in
    the output list as a shorthand for all the columns of the selected
    rows.  Also, one can write <literal><replaceable
    class="parameter">table_name</replaceable>.*</literal> as a
    shorthand for the columns coming from just that table.
   </para>
  </refsect2>
484 485 486
  
  <refsect2 id="SQL-UNION">
   <title id="sql-union-title"><literal>UNION</literal> Clause</title>
487 488

   <para>
489 490 491 492 493 494 495 496 497 498 499 500
    The <literal>UNION</literal> clause has this general form:
<synopsis>
<replaceable class="parameter">select_statement</replaceable> UNION [ ALL ] <replaceable class="parameter">select_statement</replaceable>
</synopsis>
    <replaceable class="parameter">select_statement</replaceable> is
    any <command>SELECT</command> statement without an <literal>ORDER
    BY</>, <literal>LIMIT</>, or <literal>FOR UPDATE</literal> clause.
    (<literal>ORDER BY</> and <literal>LIMIT</> can be attached to a
    subexpression if it is enclosed in parentheses.  Without
    parentheses, these clauses will be taken to apply to the result of
    the <literal>UNION</literal>, not to its right-hand input
    expression.)
501
   </para>
502
    
503
   <para>
504 505 506 507 508 509 510 511
    The <literal>UNION</literal> operator computes the set union of
    the rows returned by the involved <command>SELECT</command>
    statements.  A row is in the set union of two result sets if it
    appears in at least one of the result sets.  The two
    <command>SELECT</command> statements that represent the direct
    operands of the <literal>UNION</literal> must produce the same
    number of columns, and corresponding columns must be of compatible
    data types.
512
   </para>
513
    
514
   <para>
515 516
    The result of <literal>UNION</> does not contain any duplicate
    rows unless the <literal>ALL</> option is specified.
517 518 519
    <literal>ALL</> prevents elimination of duplicates.  (Therefore,
    <literal>UNION ALL</> is usually significantly quicker than
    <literal>UNION</>; use <literal>ALL</> when you can.)
520
   </para>
521
    
522
   <para>
523 524 525
    Multiple <literal>UNION</> operators in the same
    <command>SELECT</command> statement are evaluated left to right,
    unless otherwise indicated by parentheses.
526
   </para>
527 528
    
   <para>
529
    Currently, <literal>FOR UPDATE</> may not be specified either for
Tom Lane's avatar
Tom Lane committed
530
    a <literal>UNION</> result or for any input of a <literal>UNION</>.
531
   </para>
532
  </refsect2>
533

534 535
  <refsect2 id="SQL-INTERSECT">
   <title id="sql-intersect-title"><literal>INTERSECT</literal> Clause</title>
536 537

   <para>
538 539 540 541 542 543 544
    The <literal>INTERSECT</literal> clause has this general form:
<synopsis>
<replaceable class="parameter">select_statement</replaceable> INTERSECT [ ALL ] <replaceable class="parameter">select_statement</replaceable>
</synopsis>
    <replaceable class="parameter">select_statement</replaceable> is
    any <command>SELECT</command> statement without an <literal>ORDER
    BY</>, <literal>LIMIT</>, or <literal>FOR UPDATE</literal> clause.
545
   </para>
546

547
   <para>
548 549 550 551
    The <literal>INTERSECT</literal> operator computes the set
    intersection of the rows returned by the involved
    <command>SELECT</command> statements.  A row is in the
    intersection of two result sets if it appears in both result sets.
552
   </para>
553 554
    
   <para>
555 556
    The result of <literal>INTERSECT</literal> does not contain any
    duplicate rows unless the <literal>ALL</> option is specified.
557 558 559
    With <literal>ALL</>, a row that has <replaceable>m</> duplicates in the
    left table and <replaceable>n</> duplicates in the right table will appear
    min(<replaceable>m</>,<replaceable>n</>) times in the result set.
560
   </para>
561
    
562
   <para>
563 564 565 566 567 568 569
    Multiple <literal>INTERSECT</literal> operators in the same
    <command>SELECT</command> statement are evaluated left to right,
    unless parentheses dictate otherwise.
    <literal>INTERSECT</literal> binds more tightly than
    <literal>UNION</literal>.  That is, <literal>A UNION B INTERSECT
    C</literal> will be read as <literal>A UNION (B INTERSECT
    C)</literal>.
570
   </para>
571 572 573 574 575
    
   <para>
    Currently, <literal>FOR UPDATE</> may not be specified either for
    an <literal>INTERSECT</> result or for any input of an <literal>INTERSECT</>.
   </para>
576
  </refsect2>
577 578 579 580

  <refsect2 id="SQL-EXCEPT">
   <title id="sql-except-title"><literal>EXCEPT</literal> Clause</title>

581
   <para>
582 583 584 585 586 587 588
    The <literal>EXCEPT</literal> clause has this general form:
<synopsis>
<replaceable class="parameter">select_statement</replaceable> EXCEPT [ ALL ] <replaceable class="parameter">select_statement</replaceable>
</synopsis>
    <replaceable class="parameter">select_statement</replaceable> is
    any <command>SELECT</command> statement without an <literal>ORDER
    BY</>, <literal>LIMIT</>, or <literal>FOR UPDATE</literal> clause.
589
   </para>
590

591
   <para>
592 593 594 595
    The <literal>EXCEPT</literal> operator computes the set of rows
    that are in the result of the left <command>SELECT</command>
    statement but not in the result of the right one.
   </para>
596 597
    
   <para>
598 599
    The result of <literal>EXCEPT</literal> does not contain any
    duplicate rows unless the <literal>ALL</> option is specified.
600 601 602
    With <literal>ALL</>, a row that has <replaceable>m</> duplicates in the
    left table and <replaceable>n</> duplicates in the right table will appear
    max(<replaceable>m</>-<replaceable>n</>,0) times in the result set.
603 604 605
   </para>
    
   <para>
606 607 608 609
    Multiple <literal>EXCEPT</literal> operators in the same
    <command>SELECT</command> statement are evaluated left to right,
    unless parentheses dictate otherwise.  <literal>EXCEPT</> binds at
    the same level as <literal>UNION</>.
610
   </para>
611
    
612
   <para>
613 614
    Currently, <literal>FOR UPDATE</> may not be specified either for
    an <literal>EXCEPT</> result or for any input of an <literal>EXCEPT</>.
615
   </para>
616 617 618 619
  </refsect2>

  <refsect2 id="SQL-ORDERBY">
   <title id="sql-orderby-title"><literal>ORDER BY</literal> Clause</title>
620

621
   <para>
622 623 624 625 626 627
    The optional <literal>ORDER BY</literal> clause has this general form:
<synopsis>
ORDER BY <replaceable class="parameter">expression</replaceable> [ ASC | DESC | USING <replaceable class="parameter">operator</replaceable> ] [, ...]
</synopsis>
    <replaceable class="parameter">expression</replaceable> can be the
    name or ordinal number of an output column
Tom Lane's avatar
Tom Lane committed
628
    (<command>SELECT</command> list item), or it can be an arbitrary
629
    expression formed from input-column values.
630 631
   </para>

632
   <para>
633 634 635 636 637
    The <literal>ORDER BY</literal> clause causes the result rows to
    be sorted according to the specified expressions.  If two rows are
    equal according to the leftmost expression, the are compared
    according to the next expression and so on.  If they are equal
    according to all specified expressions, they are returned in
Tom Lane's avatar
Tom Lane committed
638
    an implementation-dependent order.
639
   </para>
640

641
   <para>
642 643 644 645 646 647
    The ordinal number refers to the ordinal (left-to-right) position
    of the result column. This feature makes it possible to define an
    ordering on the basis of a column that does not have a unique
    name.  This is never absolutely necessary because it is always
    possible to assign a name to a result column using the
    <literal>AS</> clause.
648
   </para>
649 650
    
   <para>
651 652 653 654 655 656 657 658 659 660 661
    It is also possible to use arbitrary expressions in the
    <literal>ORDER BY</literal> clause, including columns that do not
    appear in the <command>SELECT</command> result list.  Thus the
    following statement is valid:
<programlisting>
SELECT name FROM distributors ORDER BY code;
</programlisting>
    A limitation of this feature is that an <literal>ORDER BY</>
    clause applying to the result of a <literal>UNION</>,
    <literal>INTERSECT</>, or <literal>EXCEPT</> clause may only
    specify an output column name or number, not an expression.
662
   </para>
663

664
   <para>
665 666 667 668 669 670
    If an <literal>ORDER BY</> expression is a simple name that
    matches both a result column name and an input column name,
    <literal>ORDER BY</> will interpret it as the result column name.
    This is the opposite of the choice that <literal>GROUP BY</> will
    make in the same situation.  This inconsistency is made to be
    compatible with the SQL standard.
671 672 673
   </para>
    
   <para>
674
    Optionally one may add the key word <literal>ASC</> (ascending) or
Tom Lane's avatar
Tom Lane committed
675
    <literal>DESC</> (descending) after any expression in the
676 677 678
    <literal>ORDER BY</> clause.  If not specified, <literal>ASC</> is
    assumed by default.  Alternatively, a specific ordering operator
    name may be specified in the <literal>USING</> clause.
679 680
    <literal>ASC</> is usually equivalent to <literal>USING &lt;</> and
    <literal>DESC</> is usually equivalent to <literal>USING &gt;</>.
681
    (But the creator of a user-defined data type can define exactly what the
682 683
    default sort ordering is, and it might correspond to operators with other
    names.)
684 685
   </para>

686
   <para>
687 688 689
    The null value sorts higher than any other value. In other words,
    with ascending sort order, null values sort at the end, and with
    descending sort order, null values sort at the beginning.
690 691
   </para>

692
   <para>
693
    Character-string data is sorted according to the locale-specific
694 695
    collation order that was established when the database cluster
    was initialized.
696
   </para>
697
  </refsect2>
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736

  <refsect2 id="sql-distinct">
   <title id="sql-distinct-title"><literal>DISTINCT</literal> Clause</title>

   <para>
    If <literal>DISTINCT</> is specified, all duplicate rows are
    removed from the result set (one row is kept from each group of
    duplicates).  <literal>ALL</> specifies the opposite: all rows are
    kept; that is the default.
   </para>

   <para>
    <literal>DISTINCT ON ( <replaceable
    class="parameter">expression</replaceable> [, ...] )</literal>
    keeps only the first row of each set of rows where the given
    expressions evaluate to equal.  The <literal>DISTINCT ON</literal>
    expressions are interpreted using the same rules as for
    <literal>ORDER BY</> (see above).  Note that the <quote>first
    row</quote> of each set is unpredictable unless <literal>ORDER
    BY</> is used to ensure that the desired row appears first.  For
    example,
<programlisting>
SELECT DISTINCT ON (location) location, time, report
    FROM weather_reports
    ORDER BY location, time DESC;
</programlisting>
    retrieves the most recent weather report for each location.  But
    if we had not used <literal>ORDER BY</> to force descending order
    of time values for each location, we'd have gotten a report from
    an unpredictable time for each location.
   </para>

   <para>
    The <literal>DISTINCT ON</> expression(s) must match the leftmost
    <literal>ORDER BY</> expression(s).  The <literal>ORDER BY</> clause
    will normally contain additional expression(s) that determine the
    desired precedence of rows within each <literal>DISTINCT ON</> group.
   </para>
  </refsect2>
737 738 739
  
  <refsect2 id="SQL-LIMIT">
   <title id="sql-limit-title"><literal>LIMIT</literal> Clause</title>
740 741

   <para>
742
    The <literal>LIMIT</literal> clause consists of two independent
Tom Lane's avatar
Tom Lane committed
743
    sub-clauses:
744 745 746 747 748
<synopsis>
LIMIT { <replaceable class="parameter">count</replaceable> | ALL }
OFFSET <replaceable class="parameter">start</replaceable>
</synopsis>
    <replaceable class="parameter">count</replaceable> specifies the
Tom Lane's avatar
Tom Lane committed
749
    maximum number of rows to return, while <replaceable
750
    class="parameter">start</replaceable> specifies the number of rows
Tom Lane's avatar
Tom Lane committed
751 752 753 754
    to skip before starting to return rows.  When both are specified,
    <replaceable class="parameter">start</replaceable> rows are skipped
    before starting to count the <replaceable
    class="parameter">count</replaceable> rows to be returned.
755 756
   </para>

757
   <para>
758 759 760
    When using <literal>LIMIT</>, it is a good idea to use an
    <literal>ORDER BY</> clause that constrains the result rows into a
    unique order.  Otherwise you will get an unpredictable subset of
761
    the query's rows &mdash; you may be asking for the tenth through
762 763
    twentieth rows, but tenth through twentieth in what ordering?  You
    don't know what ordering unless you specify <literal>ORDER BY</>.
764 765 766
   </para>

   <para>
767 768 769 770 771 772 773 774 775 776 777
    The query planner takes <literal>LIMIT</> into account when
    generating a query plan, so you are very likely to get different
    plans (yielding different row orders) depending on what you use
    for <literal>LIMIT</> and <literal>OFFSET</>.  Thus, using
    different <literal>LIMIT</>/<literal>OFFSET</> values to select
    different subsets of a query result <emphasis>will give
    inconsistent results</emphasis> unless you enforce a predictable
    result ordering with <literal>ORDER BY</>.  This is not a bug; it
    is an inherent consequence of the fact that SQL does not promise
    to deliver the results of a query in any particular order unless
    <literal>ORDER BY</> is used to constrain the order.
778
   </para>
779
  </refsect2>
780

781
  <refsect2 id="SQL-FOR-UPDATE">
782 783
   <title id="sql-for-update-title"><literal>FOR UPDATE</literal> Clause</title>

784
   <para>
785 786 787 788
    The <literal>FOR UPDATE</literal> clause has this form:
<synopsis>
FOR UPDATE [ OF <replaceable class="parameter">table_name</replaceable> [, ...] ]
</synopsis>
789 790 791
   </para>

   <para>
792 793 794 795 796 797 798 799 800 801
    <literal>FOR UPDATE</literal> causes the rows retrieved by the
    <command>SELECT</command> statement to be locked as though for
    update.  This prevents them from being modified or deleted by
    other transactions until the current transaction ends.  That is,
    other transactions that attempt <command>UPDATE</command>,
    <command>DELETE</command>, or <command>SELECT FOR UPDATE</command>
    of these rows will be blocked until the current transaction ends.
    Also, if an <command>UPDATE</command>, <command>DELETE</command>,
    or <command>SELECT FOR UPDATE</command> from another transaction
    has already locked a selected row or rows, <command>SELECT FOR
802 803
    UPDATE</command> will wait for the other transaction to complete,
    and will then lock and return the updated row (or no row, if the
804 805
    row was deleted).  For further discussion see <xref
    linkend="mvcc">.
806 807 808
   </para>

   <para>
809 810 811 812
    If specific tables are named in <literal>FOR UPDATE</literal>,
    then only rows coming from those tables are locked; any other
    tables used in the <command>SELECT</command> are simply read as
    usual.
813 814 815
   </para>

   <para>
816 817 818
    <literal>FOR UPDATE</literal> cannot be used in contexts where
    returned rows can't be clearly identified with individual table
    rows; for example it can't be used with aggregation.
Tom Lane's avatar
Tom Lane committed
819 820 821
   </para>

   <para>
822
    <literal>FOR UPDATE</literal> may appear before
823 824 825 826
    <literal>LIMIT</literal> for compatibility with
    <productname>PostgreSQL</productname> versions before 7.3.  It
    effectively executes after <literal>LIMIT</literal>, however, and
    so that is the recommended place to write it.
827 828
   </para>
  </refsect2>
829
 </refsect1>
830

831 832
 <refsect1>
  <title>Examples</title>
833

834 835 836
  <para>
   To join the table <literal>films</literal> with the table
   <literal>distributors</literal>:
837

838
<programlisting>
839 840 841
SELECT f.title, f.did, d.name, f.date_prod, f.kind
    FROM distributors d, films f
    WHERE f.did = d.did
842

843 844 845 846 847
       title       | did |     name     | date_prod  |   kind
-------------------+-----+--------------+------------+----------
 The Third Man     | 101 | British Lion | 1949-12-23 | Drama
 The African Queen | 101 | British Lion | 1951-08-11 | Romantic
 ...
848
</programlisting>
849 850
  </para>

851 852
  <para>
   To sum the column <literal>len</literal> of all films and group
853
   the results by <literal>kind</literal>:
854

855
<programlisting>
856
SELECT kind, sum(len) AS total FROM films GROUP BY kind;
857

858 859 860 861 862 863 864 865
   kind   | total
----------+-------
 Action   | 07:34
 Comedy   | 02:58
 Drama    | 14:28
 Musical  | 06:42
 Romantic | 04:38
</programlisting>
866
  </para>
867 868 869

  <para>
   To sum the column <literal>len</literal> of all films, group
870
   the results by <literal>kind</literal> and show those group totals
871
   that are less than 5 hours:
872

873
<programlisting>
874
SELECT kind, sum(len) AS total
875 876
    FROM films
    GROUP BY kind
877
    HAVING sum(len) < interval '5 hours';
878

879
   kind   | total
880 881 882 883
----------+-------
 Comedy   | 02:58
 Romantic | 04:38
</programlisting>
884 885
  </para>

886
  <para>
887
   The following two examples are identical ways of sorting the individual
888 889
   results according to the contents of the second column
   (<literal>name</literal>):
890

891
<programlisting>
892 893
SELECT * FROM distributors ORDER BY name;
SELECT * FROM distributors ORDER BY 2;
894

895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910
 did |       name
-----+------------------
 109 | 20th Century Fox
 110 | Bavaria Atelier
 101 | British Lion
 107 | Columbia
 102 | Jean Luc Godard
 113 | Luso films
 104 | Mosfilm
 103 | Paramount
 106 | Toho
 105 | United Artists
 111 | Walt Disney
 112 | Warner Bros.
 108 | Westward
</programlisting>
911
  </para>
912 913

  <para>
Tom Lane's avatar
Tom Lane committed
914
   The next example shows how to obtain the union of the tables
915 916
   <literal>distributors</literal> and
   <literal>actors</literal>, restricting the results to those that begin
Tom Lane's avatar
Tom Lane committed
917
   with the letter W in each table.  Only distinct rows are wanted, so the
918
   key word <literal>ALL</literal> is omitted.
919

920 921 922 923 924 925 926 927
<programlisting>
distributors:               actors:
 did |     name              id |     name
-----+--------------        ----+----------------
 108 | Westward               1 | Woody Allen
 111 | Walt Disney            2 | Warren Beatty
 112 | Warner Bros.           3 | Walter Matthau
 ...                         ...
928

929
SELECT distributors.name
930 931
    FROM distributors
    WHERE distributors.name LIKE 'W%'
932 933
UNION
SELECT actors.name
934 935
    FROM actors
    WHERE actors.name LIKE 'W%';
936

937 938 939 940 941 942 943 944
      name
----------------
 Walt Disney
 Walter Matthau
 Warner Bros.
 Warren Beatty
 Westward
 Woody Allen
945 946 947 948
</programlisting>
  </para>

  <para>
949
   This example shows how to use a function in the <literal>FROM</>
Tom Lane's avatar
Tom Lane committed
950
   clause, both with and without a column definition list:
951 952

<programlisting>
953
CREATE FUNCTION distributors(int) RETURNS SETOF distributors AS $$
954
    SELECT * FROM distributors WHERE did = $1;
955
$$ LANGUAGE SQL;
956 957 958 959 960 961

SELECT * FROM distributors(111);
 did |    name
-----+-------------
 111 | Walt Disney

962
CREATE FUNCTION distributors_2(int) RETURNS SETOF record AS $$
963
    SELECT * FROM distributors WHERE did = $1;
964
$$ LANGUAGE SQL;
965 966 967 968 969

SELECT * FROM distributors_2(111) AS (f1 int, f2 text);
 f1  |     f2
-----+-------------
 111 | Walt Disney
970
</programlisting>
971
  </para>
972 973
 </refsect1>
 
974 975 976 977 978 979 980 981
 <refsect1>
  <title>Compatibility</title>

  <para>
   Of course, the <command>SELECT</command> statement is compatible
   with the SQL standard.  But there are some extensions and some
   missing features.
  </para>
982
  
983 984
  <refsect2>
   <title>Omitted <literal>FROM</literal> Clauses</title>
985 986

   <para>
987 988 989 990
    <productname>PostgreSQL</productname> allows one to omit the
    <literal>FROM</literal> clause.  It has a straightforward use to
    compute the results of simple expressions:
<programlisting>
991 992 993 994 995
SELECT 2+2;

 ?column?
----------
        4
996 997 998 999 1000
</programlisting>
    Some other <acronym>SQL</acronym> databases cannot do this except
    by introducing a dummy one-row table from which to do the
    <command>SELECT</command>.
   </para>
1001

1002 1003 1004 1005
   <para>
    A less obvious use is to abbreviate a normal
    <command>SELECT</command> from tables:
<programlisting>
1006
SELECT distributors.* WHERE distributors.name = 'Westward';
1007

1008
 did |   name
1009 1010
-----+----------
 108 | Westward
1011 1012 1013 1014 1015 1016
</programlisting>
    This works because an implicit <literal>FROM</literal> item is
    added for each table that is referenced in other parts of the
    <command>SELECT</command> statement but not mentioned in
    <literal>FROM</literal>.
   </para>
1017

1018 1019 1020 1021
   <para>
    While this is a convenient shorthand, it's easy to misuse.  For
    example, the command
<programlisting>
1022
SELECT distributors.* FROM distributors d;
1023 1024 1025
</programlisting>
    is probably a mistake; most likely the user meant
<programlisting>
1026
SELECT d.* FROM distributors d;
1027 1028 1029
</programlisting>
    rather than the unconstrained join
<programlisting>
1030
SELECT distributors.* FROM distributors d, distributors distributors;
1031 1032
</programlisting>
    that he will actually get.  To help detect this sort of mistake,
1033 1034 1035 1036 1037
    <productname>PostgreSQL</productname> will warn if the
    implicit-<literal>FROM</literal> feature is used in a
    <command>SELECT</command> statement that also contains an explicit
    <literal>FROM</literal> clause.  Also, it is possible to disable
    the implicit-<literal>FROM</literal> feature by setting the
1038
    <xref linkend="guc-add-missing-from"> parameter to false.
1039 1040 1041 1042 1043
   </para>
  </refsect2>

  <refsect2>
   <title>The <literal>AS</literal> Key Word</title>
1044

1045 1046 1047 1048 1049
   <para>
    In the SQL standard, the optional key word <literal>AS</> is just
    noise and can be omitted without affecting the meaning.  The
    <productname>PostgreSQL</productname> parser requires this key
    word when renaming output columns because the type extensibility
1050
    features lead to parsing ambiguities without it.
1051 1052
    <literal>AS</literal> is optional in <literal>FROM</literal>
    items, however.
1053
   </para>
1054 1055 1056 1057
  </refsect2>

  <refsect2>
   <title>Namespace Available to <literal>GROUP BY</literal> and <literal>ORDER BY</literal></title>
1058 1059

   <para>
1060
    In the SQL-92 standard, an <literal>ORDER BY</literal> clause may
1061 1062 1063 1064 1065 1066 1067 1068 1069
    only use result column names or numbers, while a <literal>GROUP
    BY</literal> clause may only use expressions based on input column
    names.  <productname>PostgreSQL</productname> extends each of
    these clauses to allow the other choice as well (but it uses the
    standard's interpretation if there is ambiguity).
    <productname>PostgreSQL</productname> also allows both clauses to
    specify arbitrary expressions.  Note that names appearing in an
    expression will always be taken as input-column names, not as
    result-column names.
1070
   </para>
1071 1072

   <para>
1073
    SQL:1999 uses a slightly different definition which is not entirely upward
Tom Lane's avatar
Tom Lane committed
1074
    compatible 
1075
    with SQL-92.  In most cases, however, <productname>PostgreSQL</productname>
1076
    will interpret an <literal>ORDER BY</literal> or <literal>GROUP
1077
    BY</literal> expression the same way SQL:1999 does.
1078
   </para>
1079
  </refsect2>
1080

1081 1082 1083
  <refsect2>
   <title>Nonstandard Clauses</title>

1084
   <para>
1085 1086 1087
    The clauses <literal>DISTINCT ON</literal>,
    <literal>LIMIT</literal>, and <literal>OFFSET</literal> are not
    defined in the SQL standard.
1088 1089 1090 1091 1092 1093 1094 1095
   </para>
  </refsect2>
 </refsect1>
</refentry>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
1096
sgml-omittag:nil
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
sgml-parent-document:nil
sgml-default-dtd-file:"../reference.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:"/usr/lib/sgml/catalog"
sgml-local-ecat-files:nil
End:
1108
-->