select.sgml 41.0 KB
Newer Older
1
<!--
P
Peter Eisentraut 已提交
2
$Header: /cvsroot/pgsql/doc/src/sgml/ref/select.sgml,v 1.61 2002/09/21 18:32:54 petere Exp $
3
PostgreSQL documentation
4 5
-->

6 7
<refentry id="SQL-SELECT">
 <refmeta>
8
  <refentrytitle id="sql-select-title">SELECT</refentrytitle>
9 10 11 12
  <refmiscinfo>SQL - Language Statements</refmiscinfo>
 </refmeta>
 <refnamediv>
  <refname>
13
   SELECT
14 15
  </refname>
  <refpurpose>
16
   retrieve rows from a table or view
17 18 19
  </refpurpose></refnamediv>
 <refsynopsisdiv>
  <refsynopsisdivinfo>
20
   <date>2000-12-11</date>
21 22
  </refsynopsisdivinfo>
  <synopsis>
23
SELECT [ ALL | DISTINCT [ ON ( <replaceable class="PARAMETER">expression</replaceable> [, ...] ) ] ]
24 25
    * | <replaceable class="PARAMETER">expression</replaceable> [ AS <replaceable class="PARAMETER">output_name</replaceable> ] [, ...]
    [ FROM <replaceable class="PARAMETER">from_item</replaceable> [, ...] ]
26
    [ WHERE <replaceable class="PARAMETER">condition</replaceable> ]
27
    [ GROUP BY <replaceable class="PARAMETER">expression</replaceable> [, ...] ]
28
    [ HAVING <replaceable class="PARAMETER">condition</replaceable> [, ...] ]
29
    [ { UNION | INTERSECT | EXCEPT } [ ALL ] <replaceable class="PARAMETER">select</replaceable> ]
30
    [ ORDER BY <replaceable class="PARAMETER">expression</replaceable> [ ASC | DESC | USING <replaceable class="PARAMETER">operator</replaceable> ] [, ...] ]
31
    [ LIMIT { <replaceable class="PARAMETER">count</replaceable> | ALL } ]
B
Bruce Momjian 已提交
32
    [ OFFSET <replaceable class="PARAMETER">start</replaceable> ]
33
    [ FOR UPDATE [ OF <replaceable class="PARAMETER">tablename</replaceable> [, ...] ] ]
34 35 36 37 38 39 40 41 42

where <replaceable class="PARAMETER">from_item</replaceable> can be:

[ ONLY ] <replaceable class="PARAMETER">table_name</replaceable> [ * ]
    [ [ AS ] <replaceable class="PARAMETER">alias</replaceable> [ ( <replaceable class="PARAMETER">column_alias_list</replaceable> ) ] ]
|
( <replaceable class="PARAMETER">select</replaceable> )
    [ AS ] <replaceable class="PARAMETER">alias</replaceable> [ ( <replaceable class="PARAMETER">column_alias_list</replaceable> ) ]
|
43
<replaceable class="PARAMETER">table_function_name</replaceable> ( [ <replaceable class="parameter">argument</replaceable> [, ...] ] )
44 45
    [ AS ] <replaceable class="PARAMETER">alias</replaceable> [ ( <replaceable class="PARAMETER">column_alias_list</replaceable> | <replaceable class="PARAMETER">column_definition_list</replaceable> ) ]
|
46
<replaceable class="PARAMETER">table_function_name</replaceable> ( [ <replaceable class="parameter">argument</replaceable> [, ...] ] )
47 48
    AS ( <replaceable class="PARAMETER">column_definition_list</replaceable> )
|
49 50
<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_list</replaceable> ) ]
51 52 53 54
  </synopsis>
  
  <refsect2 id="R2-SQL-SELECT-1">
   <refsect2info>
55
    <date>2000-12-11</date>
56 57 58 59
   </refsect2info>
   <title>
    Inputs
   </title>
60

61 62 63
   <para>
    <variablelist>
     <varlistentry>
64
      <term><replaceable class="PARAMETER">expression</replaceable></term>
65 66 67 68 69 70 71 72
      <listitem>
       <para>
	The name of a table's column or an expression.
       </para>
      </listitem>
     </varlistentry>
     
     <varlistentry>
73
      <term><replaceable class="PARAMETER">output_name</replaceable></term>
74 75
      <listitem>
       <para>
76
	Specifies another name for an output column using
77 78 79
	the AS clause.  This name is primarily used to label the column
	for display.  It can also be used to refer to the column's value in
	ORDER BY and GROUP BY clauses.  But the
80
	<replaceable class="PARAMETER">output_name</replaceable>
81 82
	cannot be used in the WHERE or HAVING clauses; write out the
	expression instead.
83 84 85 86 87
       </para>
      </listitem>
     </varlistentry>
     
     <varlistentry>
88
      <term><replaceable class="PARAMETER">from_item</replaceable></term>
89 90
      <listitem>
       <para>
91
        A table reference, sub-SELECT, table function, or JOIN clause.  See below for details.
92 93 94 95 96
       </para>
      </listitem>
     </varlistentry>
     
     <varlistentry>
97
      <term><replaceable class="PARAMETER">condition</replaceable></term>
98 99
      <listitem>
       <para>
100
	A Boolean expression giving a result of true or false.
101
	See the WHERE and HAVING clause descriptions below.
102 103 104 105 106
       </para>
      </listitem>
     </varlistentry>
     
     <varlistentry>
107
      <term><replaceable class="PARAMETER">select</replaceable></term>
108 109
      <listitem>
       <para>
110 111 112
	A select statement with all features except the ORDER BY, 
	LIMIT/OFFSET, and FOR UPDATE clauses (even those can be used when the 
	select is parenthesized).
113 114 115 116
       </para>
      </listitem>
     </varlistentry>
     
117 118 119 120 121 122 123
    </variablelist>
   </para>

   <para>
    FROM items can contain:
    <variablelist>
     
124
     <varlistentry>
125
      <term><replaceable class="PARAMETER">table_name</replaceable></term>
126 127
      <listitem>
       <para>
128 129 130 131 132 133
	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
134 135 136
	before 7.1, <literal>ONLY</> was the default behavior.)  The
	default behavior can be modified by changing the
	<option>SQL_INHERITANCE</option> configuration option.
137 138 139 140 141 142 143 144
       </para>
      </listitem>
     </varlistentry>
     
     <varlistentry>
      <term><replaceable class="PARAMETER">alias</replaceable></term>
      <listitem>
       <para>
145
	A substitute name for the FROM item containing the alias.
146
	An alias is used for brevity or to eliminate ambiguity for self-joins
147 148 149 150 151 152
	(where the same table is scanned multiple times).  When an alias
	is provided, it completely hides the actual name of the table or
	table function; for example given <literal>FROM foo AS f</>, the
	remainder of the SELECT must refer to this FROM item as <literal>f</>
	not <literal>foo</>.
	If an alias is
153 154
	written, a column alias list can also be written to provide
	substitute names for one or more columns of the table.
155 156 157 158 159
       </para>
      </listitem>
     </varlistentry>
     
     <varlistentry>
160
      <term><replaceable class="PARAMETER">select</replaceable></term>
161 162
      <listitem>
       <para>
163 164 165 166 167 168 169 170
	A sub-SELECT can appear in the FROM clause.  This acts as though
	its output were created as a temporary table for the duration of
	this single SELECT command.  Note that the sub-SELECT must be
	surrounded by parentheses, and an alias <emphasis>must</emphasis>
	be provided for it.
       </para>
      </listitem>
     </varlistentry>
171 172 173 174 175 176 177 178

     <varlistentry>
      <term><replaceable class="PARAMETER">table function</replaceable></term>
      <listitem>
       <para>
	A table function can appear in the FROM clause.  This acts as though
	its output were created as a temporary table for the duration of
	this single SELECT command. An alias may also be used. If an alias is
179 180 181 182 183 184 185 186 187
	written, a column alias list can also be written to provide substitute
	names for one or more columns of the table function. If the table
	function has been defined as returning the <type>record</> data type,
	an alias, or the keyword <literal>AS</>, must be present, followed by
	a column definition list in the form ( <replaceable
	class="PARAMETER">column_name</replaceable> <replaceable
	class="PARAMETER">data_type</replaceable> [, ... ] ).
	The column definition list must match the actual number and types
	of columns returned by the function.
188 189 190
       </para>
      </listitem>
     </varlistentry>
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
     
     <varlistentry>
      <term><replaceable class="PARAMETER">join_type</replaceable></term>
      <listitem>
       <para>
       One of
       <command>[ INNER ] JOIN</command>,
       <command>LEFT [ OUTER ] JOIN</command>,
       <command>RIGHT [ OUTER ] JOIN</command>,
       <command>FULL [ OUTER ] JOIN</command>, or
       <command>CROSS JOIN</command>.
       For INNER and OUTER join types, exactly one of NATURAL,
       ON <replaceable class="PARAMETER">join_condition</replaceable>, or
       USING ( <replaceable class="PARAMETER">join_column_list</replaceable> )
       must appear.  For CROSS JOIN, none of these items may appear.
       </para>
      </listitem>
     </varlistentry>
     
     <varlistentry>
      <term><replaceable class="PARAMETER">join_condition</replaceable></term>
      <listitem>
       <para>
       A qualification condition.  This is similar to the WHERE condition
       except that it only applies to the two from_items being joined in
       this JOIN clause.
217 218 219 220
       </para>
      </listitem>
     </varlistentry>
     
221 222 223 224 225 226 227 228 229 230
     <varlistentry>
      <term><replaceable class="PARAMETER">join_column_list</replaceable></term>
      <listitem>
       <para>
       A USING column list ( a, b, ... ) is shorthand for the ON condition
       left_table.a = right_table.a AND left_table.b = right_table.b ...
       </para>
      </listitem>
     </varlistentry>

231 232 233 234 235 236
    </variablelist>
   </para>
  </refsect2>
  
  <refsect2 id="R2-SQL-SELECT-2">
   <refsect2info>
237
    <date>1998-09-24</date>
238 239 240 241
   </refsect2info>
   <title>
    Outputs
   </title>
242
   <para>
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264

    <variablelist>
     <varlistentry>
      <term>Rows</term>
      <listitem>
       <para>
	The complete set of rows resulting from the query specification.
       </para>
      </listitem>
     </varlistentry>

     <varlistentry>
      <term>
       <returnvalue><replaceable>count</replaceable></returnvalue>
      </term>
      <listitem>
       <para>
	The count of rows returned by the query.
       </para>
      </listitem>
     </varlistentry>
    </variablelist>
265
   </para>
266 267
  </refsect2>
 </refsynopsisdiv>
268

269 270
 <refsect1 id="R1-SQL-SELECT-1">
  <refsect1info>
271
   <date>2000-12-11</date>
272 273 274 275 276
  </refsect1info>
  <title>
   Description
  </title>
  <para>
277 278
   <command>SELECT</command> will return rows from one or more tables.
   Candidates for selection are rows which satisfy the WHERE condition;
279
   if WHERE is omitted, all rows are candidates.
280
   (See <xref linkend="sql-where" endterm="sql-where-title">.)
281
  </para>
282

283
  <para>
284 285 286 287 288 289 290
   Actually, the returned rows are not directly the rows produced by the
   FROM/WHERE/GROUP BY/HAVING clauses; rather, the output rows are formed
   by computing the SELECT output expressions for each selected row.
   <command>*</command> can be written in the output list as a shorthand
   for all the columns of the selected rows.  Also, one can write
   <replaceable class="PARAMETER">table_name</replaceable><command>.*</command>
   as a shorthand for the columns coming from just that table.
291
  </para>
292

293
  <para>
294
   <command>DISTINCT</command> will eliminate duplicate rows from the
295
   result.
296
   <command>ALL</command> (the default) will return all candidate rows,
297 298
   including duplicates.
  </para>
299

300 301 302
  <para>
   <command>DISTINCT ON</command> eliminates rows that match on all the
   specified expressions, keeping only the first row of each set of
303 304
   duplicates.  The DISTINCT ON expressions are interpreted using the
   same rules as for ORDER BY items; see below.
305
   Note that the <quote>first row</quote> of each set is unpredictable
306 307 308 309 310 311 312 313 314 315 316 317 318
   unless <command>ORDER BY</command> is used to ensure that the desired
   row appears first.  For example,
   <programlisting>
        SELECT DISTINCT ON (location) location, time, report
        FROM weatherReports
        ORDER BY location, time DESC;
   </programlisting>
   retrieves the most recent weather report for each location.  But if
   we had not used ORDER BY to force descending order of time values
   for each location, we'd have gotten a report of unpredictable age
   for each location.
  </para>

319
  <para>
320
   The GROUP BY clause allows a user to divide a table
321
   into groups of rows that match on one or more values.
322
   (See <xref linkend="sql-groupby" endterm="sql-groupby-title">.)
323 324
  </para>

325
  <para>
326 327
   The HAVING clause allows selection of only those groups of rows
   meeting the specified condition.
328
   (See <xref linkend="sql-having" endterm="sql-having-title">.)
329
  </para>
330 331
   
  <para>
332 333 334
   The ORDER BY clause causes the returned rows to be sorted in a specified
   order.  If ORDER BY is not given, the rows are returned in whatever order
   the system finds cheapest to produce.
335
   (See <xref linkend="sql-orderby" endterm="sql-orderby-title">.)
336
  </para>
337 338
   
  <para>
339 340 341 342 343 344 345
   SELECT queries can be combined using UNION, INTERSECT, and EXCEPT
   operators.  Use parentheses if necessary to determine the ordering
   of these operators.
  </para>
   
  <para>
   The UNION operator computes the collection of rows
346
   returned by the queries involved.
347
   Duplicate rows are eliminated unless ALL is specified.
348
   (See <xref linkend="sql-union" endterm="sql-union-title">.)
349
  </para>
350 351
   
  <para>
352 353
   The INTERSECT operator computes the rows that are common to both queries.
   Duplicate rows are eliminated unless ALL is specified.
354
   (See <xref linkend="sql-intersect" endterm="sql-intersect-title">.)
355
  </para>
356 357
   
  <para>
358
   The EXCEPT operator computes the rows returned by the first query but
359
   not the second query.
360
   Duplicate rows are eliminated unless ALL is specified.
361
   (See <xref linkend="sql-except" endterm="sql-except-title">.)
362
  </para>
363
   
364
  <para>
365 366 367
   The LIMIT clause allows a subset of the rows produced by the query
   to be returned to the user.
   (See <xref linkend="sql-limit" endterm="sql-limit-title">.)
368
  </para>
369

370 371 372 373 374
  <para>
   The FOR UPDATE clause allows the SELECT statement to perform 
   exclusive locking of selected rows.
  </para>
   
375
  <para>
376
   You must have SELECT privilege to a table to read its values
377 378
   (See the <command>GRANT</command>/<command>REVOKE</command> statements).
  </para>
379
   
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
  <refsect2 id="SQL-FROM">
   <refsect2info>
    <date>2000-12-11</date>
   </refsect2info>
   <title id="sql-from-title">
    FROM Clause
   </title>

   <para>
    The FROM clause specifies one or more source tables for the SELECT.
    If multiple sources are specified, the result is conceptually the
    Cartesian product of all the rows in all the sources --- but usually
    qualification conditions are added to restrict the returned rows to
    a small subset of the Cartesian product.
   </para>

   <para>
    When a FROM item is a simple table name, it implicitly includes rows
398
    from sub-tables (inheritance children) of the table.
399
    <command>ONLY</command> will
400
    suppress rows from sub-tables of the table.  Before
401
    <Productname>PostgreSQL</Productname> 7.1,
402
    this was the default result, and adding sub-tables was done
403
    by appending <command>*</command> to the table name.
404
    This old behavior is available via the command 
405
    <command>SET SQL_Inheritance TO OFF</command>.
406 407 408 409 410 411 412 413 414
   </para>

   <para>
    A FROM item can also be a parenthesized sub-SELECT (note that an
    alias clause is required for a sub-SELECT!).  This is an extremely
    handy feature since it's the only way to get multiple levels of
    grouping, aggregation, or sorting in a single query.
   </para>

415
   <para>
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
    A FROM item can be a table function (typically, a function that returns
    multiple rows and/or columns, though actually any function can be used).
    The function is invoked with the given argument value(s), and then its
    output is scanned as though it were a table.
   </para>

   <para>
    In some cases it is useful to define table functions that can return
    different column sets depending on how they are invoked.  To support this,
    the table function can be declared as returning the pseudo-type
    <type>record</>.  When such a function is used in FROM, it must be
    followed by an alias, or the keyword <literal>AS</> alone,
    and then by a parenthesized list of column names and types. This provides
    a query-time composite type definition. The composite type definition
    must match the actual composite type returned from the function, or an
    error will be reported at run-time.
432 433
   </para>

434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
   <para>
    Finally, a FROM item can be a JOIN clause, which combines two simpler
    FROM items.  (Use parentheses if necessary to determine the order
    of nesting.)
   </para>

   <para>
    A CROSS JOIN or INNER JOIN is a simple Cartesian product,
    the same as you get from listing the two items at the top level of FROM.
    CROSS JOIN is equivalent to INNER JOIN ON (TRUE), that is, no rows are
    removed by qualification.  These join types are just a notational
    convenience, since they do nothing you couldn't do with plain FROM and
    WHERE.
   </para>

   <para>
    LEFT OUTER JOIN returns all rows in the qualified Cartesian product
P
Peter Eisentraut 已提交
451
    (i.e., all combined rows that pass its ON condition), plus one copy of each
452 453
    row in the left-hand table for which there was no right-hand row that
    passed the ON condition.  This left-hand row is extended to the full
P
Peter Eisentraut 已提交
454 455
    width of the joined table by inserting null values for the right-hand columns.
    Note that only the <literal>JOIN</>'s own ON or USING condition is considered while
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
    deciding which rows have matches.  Outer ON or WHERE conditions are
    applied afterwards.
   </para>

   <para>
    Conversely, 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 LEFT OUTER JOIN by switching
    the left and right inputs.
   </para>

   <para>
    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).
   </para>

   <para>
    For all the JOIN types except CROSS JOIN, you must write exactly one of
    ON <replaceable class="PARAMETER">join_condition</replaceable>,
    USING ( <replaceable class="PARAMETER">join_column_list</replaceable> ),
    or NATURAL.  ON is the most general case: you can write any qualification
    expression involving the two tables to be joined.
    A USING column list ( a, b, ... ) is shorthand for the ON condition
    left_table.a = right_table.a AND left_table.b = right_table.b ...
    Also, USING implies that only one of each pair of equivalent columns will
    be included in the JOIN output, not both.  NATURAL is shorthand for
    a USING list that mentions all similarly-named columns in the tables.
   </para>
  </refsect2>
   
488
  <refsect2 id="SQL-WHERE">
489
   <refsect2info>
490
    <date>2000-03-15</date>
491
   </refsect2info>
492
   <title id="sql-where-title">
493
    WHERE Clause
494
   </title>
495

496 497 498 499
   <para>
    The optional WHERE condition has the general form:
    
    <synopsis>
500
WHERE <replaceable class="PARAMETER">boolean_expr</replaceable>
501 502
    </synopsis>
    
503
    <replaceable class="PARAMETER">boolean_expr</replaceable>
504
    can consist of any expression which evaluates to a Boolean value.
B
Bruce Momjian 已提交
505
    In many cases, this expression will be:
506 507 508 509 510 511 512 513 514 515 516 517 518 519

    <synopsis>
     <replaceable class="PARAMETER">expr</replaceable> <replaceable class="PARAMETER">cond_op</replaceable> <replaceable class="PARAMETER">expr</replaceable>
    </synopsis>

    or

    <synopsis>
     <replaceable class="PARAMETER">log_op</replaceable> <replaceable class="PARAMETER">expr</replaceable>
    </synopsis>

    where <replaceable class="PARAMETER">cond_op</replaceable>
    can be one of: =, &lt;, &lt;=, &gt;, &gt;= or &lt;&gt;,
    a conditional operator like ALL, ANY, IN, LIKE, or a
B
Bruce Momjian 已提交
520
    locally defined operator, 
521 522
    and <replaceable class="PARAMETER">log_op</replaceable> can be one 
    of: AND, OR, NOT.
523 524
    SELECT will ignore all rows for which the WHERE condition does not return
    TRUE.
525 526 527
   </para>
  </refsect2>
  
528
  <refsect2 id="SQL-GROUPBY">
529
   <refsect2info>
530
    <date>2000-03-15</date>
531
   </refsect2info>
532
   <title id="sql-groupby-title">
533
    GROUP BY Clause
534 535
   </title>
   <para>
536
    GROUP BY specifies a grouped table derived by the application
537
    of this clause:
538
    <synopsis>
539
GROUP BY <replaceable class="PARAMETER">expression</replaceable> [, ...]
540 541 542 543
    </synopsis>
   </para>

   <para>
544
    GROUP BY will condense into a single row all selected rows that share the
545 546 547 548
    same values for the grouped columns.  Aggregate functions, if any,
    are computed across all rows making up each group, producing a
    separate value for each group (whereas without GROUP BY, an
    aggregate produces a single value computed across all the selected
549 550
    rows).  When GROUP BY is present, it is not valid for the SELECT
    output expression(s) to refer to
551 552
    ungrouped columns except within aggregate functions, since there
    would be more than one possible value to return for an ungrouped column.
553
   </para>
554 555

   <para>
556 557 558 559
    A GROUP BY item can be an input column name, or the name or ordinal
    number of an output column (SELECT expression), or it can be an arbitrary
    expression formed from input-column values.  In case of ambiguity, a GROUP
    BY name will 
560 561
    be interpreted as an input-column name rather than an output column name.
   </para>
562 563
  </refsect2>

564
  <refsect2 id="SQL-HAVING">
565
   <refsect2info>
566
    <date>2000-03-15</date>
567
   </refsect2info>
568
   <title id="sql-having-title">
569
    HAVING Clause
570 571 572 573 574
   </title>
   <para>
    The optional HAVING condition has the general form:
    
    <synopsis>
575
HAVING <replaceable class="PARAMETER">boolean_expr</replaceable>
576 577
    </synopsis>
    
578
    where <replaceable class="PARAMETER">boolean_expr</replaceable> is the same
579 580
    as specified for the WHERE clause.
   </para>
581 582
    
   <para>
583
    HAVING specifies a grouped table derived by the elimination
584
    of group rows that do not satisfy the
585
    <replaceable class="PARAMETER">boolean_expr</replaceable>.
586 587 588 589
    HAVING is different from WHERE:
    WHERE filters individual rows before application of GROUP BY,
    while HAVING filters group rows created by GROUP BY.
   </para>
590

591
   <para>
592
    Each column referenced in 
593
    <replaceable class="PARAMETER">boolean_expr</replaceable> shall unambiguously
594 595
    reference a grouping column, unless the reference appears within an
    aggregate function.
596 597 598
   </para>
  </refsect2>
  
599
  <refsect2 id="SQL-ORDERBY">
600
   <refsect2info>
601
    <date>2000-03-15</date>
602
   </refsect2info>
603
   <title id="sql-orderby-title">
604
    ORDER BY Clause
605 606 607
   </title>
   <para>
    <synopsis>
608
ORDER BY <replaceable class="PARAMETER">expression</replaceable> [ ASC | DESC | USING <replaceable class="PARAMETER">operator</replaceable> ] [, ...]
609 610 611
    </synopsis></para>
    
   <para>
612 613 614 615
    An ORDER BY item can be the name or ordinal
    number of an output column (SELECT expression), or it can be an arbitrary
    expression formed from input-column values.  In case of ambiguity, an
    ORDER BY name will be interpreted as an output-column name.
616
   </para>
617
   <para>
618
    The ordinal number refers to the ordinal (left-to-right) position
619
    of the result column. This feature makes it possible to define an ordering
620
    on the basis of a column that does not have a proper name.
621
    This is never absolutely necessary because it is always possible
622
    to assign a name to a result column using the AS clause, e.g.:
623
    <programlisting>
624
SELECT title, date_prod + 1 AS newlen FROM films ORDER BY newlen;
625 626 627
    </programlisting></para>
    
   <para>
628 629 630
    It is also possible to ORDER BY
    arbitrary expressions (an extension to SQL92),
    including fields that do not appear in the
631
    SELECT result list.
632
    Thus the following statement is legal:
633
    <programlisting>
634
SELECT name FROM distributors ORDER BY code;
635
    </programlisting>
636 637 638 639 640 641
    A limitation of this feature is that an ORDER BY clause applying to the
    result of a UNION, INTERSECT, or EXCEPT query may only specify an output
    column name or number, not an expression.
   </para>
    
   <para>
642 643 644 645 646
    Note that if an ORDER BY item is a simple name that matches both
    a result column name and an input column name, ORDER BY will interpret
    it as the result column name.  This is the opposite of the choice that
    GROUP BY will make in the same situation.  This inconsistency is
    mandated by the SQL92 standard.
647
   </para>
648 649
    
   <para>
P
Peter Eisentraut 已提交
650 651 652 653 654 655 656
    Optionally one may add the key word <literal>DESC</> (descending)
    or <literal>ASC</> (ascending) after each column name in the
    <literal>ORDER BY</> clause.  If not specified, <literal>ASC</> is
    assumed by default.  Alternatively, a specific ordering operator
    name may be specified.  <literal>ASC</> is equivalent to
    <literal>USING &lt;</> and <literal>DESC</> is equivalent to
    <literal>USING &gt;</>.
657
   </para>
658 659 660 661 662 663 664

   <para>
   The null value sorts higher than any other value in a domain. In other
   words, with ascending sort order nulls sort at the end and with
   descending sort order nulls sort at the beginning.
   </para>

665 666
  </refsect2>
  
667
  <refsect2 id="SQL-UNION">
668
   <refsect2info>
669
    <date>2000-12-11</date>
670
   </refsect2info>
671
   <title id="sql-union-title">
672
    UNION Clause
673 674 675
   </title>
   <para>
    <synopsis>
676
<replaceable class="PARAMETER">table_query</replaceable> UNION [ ALL ] <replaceable class="PARAMETER">table_query</replaceable>
677
    [ ORDER BY <replaceable class="PARAMETER">expression</replaceable> [ ASC | DESC | USING <replaceable class="PARAMETER">operator</replaceable> ] [, ...] ]
678
    [ LIMIT { <replaceable class="PARAMETER">count</replaceable> | ALL } ]
B
Bruce Momjian 已提交
679
    [ OFFSET <replaceable class="PARAMETER">start</replaceable> ]
680
    </synopsis>
681

682 683
    where
    <replaceable class="PARAMETER">table_query</replaceable>
684 685
    specifies any select expression without an ORDER BY, LIMIT, or FOR UPDATE
    clause.  (ORDER BY and LIMIT can be attached to a sub-expression
686 687 688
    if it is enclosed in parentheses.  Without parentheses, these clauses
    will be taken to apply to the result of the UNION, not to its right-hand
    input expression.)
689
   </para>
690 691
    
   <para>
692
    The UNION operator computes the collection (set union) of the rows
693
    returned by the queries involved.
P
Peter Eisentraut 已提交
694
    The two SELECT statements that represent the direct operands of the UNION must
695
    produce the same number of columns, and corresponding columns must be
696 697
    of compatible data types.
   </para>
698 699
    
   <para>
700 701 702
    The result of UNION does not contain any duplicate rows
    unless the ALL option is specified.  ALL prevents elimination of
    duplicates.
703
   </para>
704 705
    
   <para>
706
    Multiple UNION operators in the same SELECT statement are
707 708 709 710 711 712
    evaluated left to right, unless otherwise indicated by parentheses.
   </para>
    
   <para>
    Currently, FOR UPDATE may not be specified either for a UNION result
    or for the inputs of a UNION.
713 714
   </para>

715 716
  </refsect2>

717
  <refsect2 id="SQL-INTERSECT">
718
   <refsect2info>
719
    <date>2000-12-11</date>
720
   </refsect2info>
721
   <title id="sql-intersect-title">
722 723 724 725
    INTERSECT Clause
   </title>
   <para>
    <synopsis>
726 727
<replaceable class="PARAMETER">table_query</replaceable> INTERSECT [ ALL ] <replaceable class="PARAMETER">table_query</replaceable>
    [ ORDER BY <replaceable class="PARAMETER">expression</replaceable> [ ASC | DESC | USING <replaceable class="PARAMETER">operator</replaceable> ] [, ...] ]
728
    [ LIMIT { <replaceable class="PARAMETER">count</replaceable> | ALL } ]
B
Bruce Momjian 已提交
729
    [ OFFSET <replaceable class="PARAMETER">start</replaceable> ]
730 731 732 733
    </synopsis>
    
    where
    <replaceable class="PARAMETER">table_query</replaceable>
734 735
    specifies any select expression without an ORDER BY, LIMIT, or 
    FOR UPDATE clause.
736 737
   </para>

738
   <para>
739 740 741 742 743 744 745 746
    INTERSECT is similar to UNION, except that it produces only rows that
    appear in both query outputs, rather than rows that appear in either.
   </para>
    
   <para>
    The result of INTERSECT does not contain any duplicate rows
    unless the ALL option is specified.  With ALL, a row that has
    m duplicates in L and n duplicates in R will appear min(m,n) times.
747
   </para>
748 749 750
    
   <para>
    Multiple INTERSECT operators in the same SELECT statement are
751
    evaluated left to right, unless parentheses dictate otherwise.
752 753 754
    INTERSECT binds more tightly than UNION --- that is,
    A UNION B INTERSECT C will be read as 
    A UNION (B INTERSECT C) unless otherwise specified by parentheses.
755
   </para>
756 757
  </refsect2>

758
  <refsect2 id="SQL-EXCEPT">
759
   <refsect2info>
760
    <date>2000-12-11</date>
761
   </refsect2info>
762
   <title id="sql-except-title">
763 764 765 766
    EXCEPT Clause
   </title>
   <para>
    <synopsis>
767 768
<replaceable class="PARAMETER">table_query</replaceable> EXCEPT [ ALL ] <replaceable class="PARAMETER">table_query</replaceable>
    [ ORDER BY <replaceable class="PARAMETER">expression</replaceable> [ ASC | DESC | USING <replaceable class="PARAMETER">operator</replaceable> ] [, ...] ]
769
    [ LIMIT { <replaceable class="PARAMETER">count</replaceable> | ALL } ]
B
Bruce Momjian 已提交
770
    [ OFFSET <replaceable class="PARAMETER">start</replaceable> ]
771
    </synopsis>
772
    
773 774
    where
    <replaceable class="PARAMETER">table_query</replaceable>
775 776
    specifies any select expression without an ORDER BY, LIMIT,
    or FOR UPDATE clause.
777 778
   </para>

779
   <para>
780 781
    EXCEPT is similar to UNION, except that it produces only rows that
    appear in the left query's output but not in the right query's output.
782
   </para>
783 784 785 786 787 788 789
    
   <para>
    The result of EXCEPT does not contain any duplicate rows
    unless the ALL option is specified.  With ALL, a row that has
    m duplicates in L and n duplicates in R will appear max(m-n,0) times.
   </para>
    
790 791
   <para>
    Multiple EXCEPT operators in the same SELECT statement are
792
    evaluated left to right, unless parentheses dictate otherwise.
793
    EXCEPT binds at the same level as UNION.
794 795 796 797 798 799 800 801 802 803 804 805
   </para>
  </refsect2>

  <refsect2 id="SQL-LIMIT">
   <refsect2info>
    <date>2000-02-20</date>
   </refsect2info>
   <title id="sql-limit-title">
    LIMIT Clause
   </title>
   <para>
    <synopsis>
806
    LIMIT { <replaceable class="PARAMETER">count</replaceable> | ALL }
807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826
    OFFSET <replaceable class="PARAMETER">start</replaceable>
    </synopsis>
    
    where
    <replaceable class="PARAMETER">count</replaceable> specifies the
    maximum number of rows to return, and
    <replaceable class="PARAMETER">start</replaceable> specifies the
    number of rows to skip before starting to return rows.
   </para>

   <para>
    LIMIT allows you to retrieve just a portion of the rows that are generated
    by the rest of the query.  If a limit count is given, no more than that
    many rows will be returned.  If an offset is given, that many rows will
    be skipped before starting to return rows.
   </para>

   <para>
    When using LIMIT, it is a good idea to use an ORDER BY clause that
    constrains the result rows into a unique order.  Otherwise you will get
B
Bruce Momjian 已提交
827
    an unpredictable subset of the query's rows---you may be asking for
828
    the tenth through twentieth rows, but tenth through twentieth in what
B
Bruce Momjian 已提交
829
    ordering?  You don't know what ordering unless you specify ORDER BY.
830 831 832
   </para>

   <para>
833
    As of <productname>PostgreSQL</productname> 7.0, the
834 835
    query optimizer takes LIMIT into account when generating a query plan,
    so you are very likely to get different plans (yielding different row
B
Bruce Momjian 已提交
836
    orders) depending on what you use for LIMIT and OFFSET.  Thus, using
837 838 839 840 841 842
    different LIMIT/OFFSET values to select different subsets of a query
    result <emphasis>will give inconsistent results</emphasis> unless
    you enforce a predictable result ordering with 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 ORDER BY is used to constrain the order.
843
   </para>
844
  </refsect2>
845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872

  <refsect2 id="SQL-FOR-UPDATE">
   <refsect2info>
    <date>2002-08-28</date>
   </refsect2info>
   <title id="sql-for-update-title">
    FOR UPDATE Clause
   </title>
   <para>
    <synopsis>
    FOR UPDATE [ OF <replaceable class="PARAMETER">tablename</replaceable> [, ...] ]
    </synopsis>
   </para>

   <para>
    FOR UPDATE causes the rows retrieved by the query to be locked as though
    for update.  This prevents them from being modified or deleted by other
    transactions until the current transaction ends.
   </para>

   <para>
    If specific tables are named in FOR UPDATE, then only rows coming from
    those tables are locked.
   </para>

   <para>
    FOR UPDATE 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
873
    aggregation.  FOR UPDATE may also appear before LIMIT for portability with
874
    pre-7.3 applications.
875 876 877
   </para>
  </refsect2>

878
 </refsect1>
879

880 881 882 883
 <refsect1 id="R1-SQL-SELECT-2">
  <title>
   Usage
  </title>
884

885 886 887
  <para>
   To join the table <literal>films</literal> with the table
   <literal>distributors</literal>:
888 889

   <programlisting>
890 891 892
SELECT f.title, f.did, d.name, f.date_prod, f.kind
    FROM distributors d, films f
    WHERE f.did = d.did
893

894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914
           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
 Une Femme est une Femme   | 102 | Jean Luc Godard  | 1961-03-12 | Romantic
 Vertigo                   | 103 | Paramount        | 1958-11-14 | Action
 Becket                    | 103 | Paramount        | 1964-02-03 | Drama
 48 Hrs                    | 103 | Paramount        | 1982-10-22 | Action
 War and Peace             | 104 | Mosfilm          | 1967-02-12 | Drama
 West Side Story           | 105 | United Artists   | 1961-01-03 | Musical
 Bananas                   | 105 | United Artists   | 1971-07-13 | Comedy
 Yojimbo                   | 106 | Toho             | 1961-06-16 | Drama
 There's a Girl in my Soup | 107 | Columbia         | 1970-06-11 | Comedy
 Taxi Driver               | 107 | Columbia         | 1975-05-15 | Action
 Absence of Malice         | 107 | Columbia         | 1981-11-15 | Action
 Storia di una donna       | 108 | Westward         | 1970-08-15 | Romantic
 The King and I            | 109 | 20th Century Fox | 1956-08-11 | Musical
 Das Boot                  | 110 | Bavaria Atelier  | 1981-11-11 | Drama
 Bed Knobs and Broomsticks | 111 | Walt Disney      |            | Musical
(17 rows)
</programlisting>
915 916
  </para>

917 918
  <para>
   To sum the column <literal>len</literal> of all films and group
919
   the results by <literal>kind</literal>:
920

921
<programlisting>
922
SELECT kind, SUM(len) AS total FROM films GROUP BY kind;
923

924 925 926 927 928 929 930 931 932
   kind   | total
----------+-------
 Action   | 07:34
 Comedy   | 02:58
 Drama    | 14:28
 Musical  | 06:42
 Romantic | 04:38
(5 rows)
</programlisting>
933
  </para>
934 935 936

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

940
<programlisting>
941 942 943 944
SELECT kind, SUM(len) AS total
    FROM films
    GROUP BY kind
    HAVING SUM(len) < INTERVAL '5 hour';
945

946 947 948 949 950 951
 kind     | total
----------+-------
 Comedy   | 02:58
 Romantic | 04:38
(2 rows)
</programlisting>
952 953
  </para>

954
  <para>
955
   The following two examples are identical ways of sorting the individual
956 957
   results according to the contents of the second column
   (<literal>name</literal>):
958 959

   <programlisting>
960 961
SELECT * FROM distributors ORDER BY name;
SELECT * FROM distributors ORDER BY 2;
962

963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979
 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
(13 rows)
</programlisting>
980
  </para>
981 982 983 984 985

  <para>
   This example shows how to obtain the union of the tables
   <literal>distributors</literal> and
   <literal>actors</literal>, restricting the results to those that begin
986
   with letter W in each table.  Only distinct rows are wanted, so the
987
   ALL keyword is omitted:
988

989 990 991 992 993 994 995 996
<programlisting>
distributors:               actors:
 did |     name              id |     name
-----+--------------        ----+----------------
 108 | Westward               1 | Woody Allen
 111 | Walt Disney            2 | Warren Beatty
 112 | Warner Bros.           3 | Walter Matthau
 ...                         ...
997

998
SELECT distributors.name
999 1000
    FROM   distributors
    WHERE  distributors.name LIKE 'W%'
1001 1002 1003
UNION
SELECT actors.name
    FROM   actors
T
Tatsuo Ishii 已提交
1004
    WHERE  actors.name LIKE 'W%';
1005

1006 1007 1008 1009 1010 1011 1012 1013
      name
----------------
 Walt Disney
 Walter Matthau
 Warner Bros.
 Warren Beatty
 Westward
 Woody Allen
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
</programlisting>
  </para>

  <para>
   This example shows how to use a table function, both with and without
   a column definition list.

<programlisting>
distributors:
 did |     name
-----+--------------
 108 | Westward
 111 | Walt Disney
 112 | Warner Bros.
 ...

CREATE FUNCTION distributors(int)
  RETURNS SETOF distributors AS '
  SELECT * FROM distributors WHERE did = $1;
  ' LANGUAGE SQL;

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

CREATE FUNCTION distributors_2(int)
  RETURNS SETOF RECORD AS '
  SELECT * FROM distributors WHERE did = $1;
  ' LANGUAGE SQL;

SELECT * FROM distributors_2(111) AS (f1 int, f2 text);
 f1  |     f2
-----+-------------
 111 | Walt Disney
(1 row)
1051
</programlisting>
1052
  </para>
1053 1054 1055 1056 1057 1058 1059 1060
 </refsect1>
 
 <refsect1 id="R1-SQL-SELECT-3">
  <title>
   Compatibility
  </title>
  
  <refsect2 id="R2-SQL-SELECT-4">
1061 1062 1063
   <refsect2info>
    <date>1998-09-24</date>
   </refsect2info>
1064
   <title>Extensions</title>
1065 1066

   <para>
1067
<productname>PostgreSQL</productname> allows one to omit 
1068
the <command>FROM</command> clause from a query. This feature
P
Peter Eisentraut 已提交
1069
was retained from the original PostQUEL query language.  It has
1070
a straightforward use to compute the results of simple expressions:
1071 1072 1073 1074 1075 1076 1077 1078 1079

  <programlisting>
SELECT 2+2;

 ?column?
----------
        4
  </programlisting>

P
Peter Eisentraut 已提交
1080
Some other SQL databases cannot do this except by introducing a dummy one-row
1081 1082 1083
table to do the select from.  A less obvious use is to abbreviate a
normal select from one or more tables:

1084
  <programlisting>
1085
SELECT distributors.* WHERE distributors.name = 'Westward';
1086

1087 1088 1089
 did | name
-----+----------
 108 | Westward
1090
  </programlisting>
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106

This works because an implicit FROM item is added for each table that is
referenced in the query but not mentioned in FROM.  While this is a convenient
shorthand, it's easy to misuse.  For example, the query
  <programlisting>
SELECT distributors.* FROM distributors d;
  </programlisting>
is probably a mistake; most likely the user meant
  <programlisting>
SELECT d.* FROM distributors d;
  </programlisting>
rather than the unconstrained join
  <programlisting>
SELECT distributors.* FROM distributors d, distributors distributors;
  </programlisting>
that he will actually get.  To help detect this sort of mistake,
1107
<Productname>PostgreSQL</Productname> 7.1
1108 1109 1110
and later will warn if the implicit-FROM feature is used in a query that also
contains an explicit FROM clause.

1111
   </para>
1112 1113 1114 1115 1116

   <para>
    The table-function feature is a <productname>PostgreSQL</productname>
    extension.
   </para>
1117
  </refsect2>
1118 1119

  <refsect2 id="R2-SQL-SELECT-5">
1120
   <refsect2info>
1121
    <date>1998-09-24</date>
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
   </refsect2info>
   <title>
    <acronym>SQL92</acronym>
   </title>
   <para>
   </para>
   
   <refsect3 id="R3-SQL-SELECT-1">
    <refsect3info>
     <date>1998-04-15</date>
    </refsect3info>
    <title>
1134
     SELECT Clause
1135 1136
    </title>
    <para>
1137
     In the <acronym>SQL92</acronym> standard, the optional keyword <literal>AS</>
1138 1139
     is just noise and can be 
     omitted without affecting the meaning.
1140
     The <productname>PostgreSQL</productname> parser requires this keyword when
1141
     renaming output columns because the type extensibility features lead to
1142
     parsing ambiguities
1143
     in this context.  <literal>AS</literal> is optional in FROM items, however.</para>
1144
     
1145 1146
    <para>
     The DISTINCT ON phrase is not part of <acronym>SQL92</acronym>.
1147
     Nor are LIMIT and OFFSET.
1148
    </para>
1149 1150 1151 1152 1153
     
    <para>
     In <acronym>SQL92</acronym>, an ORDER BY clause may only use result
     column names or numbers, while a GROUP BY clause may only use input
     column names.
1154
     <productname>PostgreSQL</productname> extends each of these clauses to
1155 1156
     allow the other choice as well (but it uses the standard's interpretation
     if there is ambiguity).
1157
     <productname>PostgreSQL</productname> also allows both clauses to specify
1158 1159 1160
     arbitrary expressions.  Note that names appearing in an expression will
     always be taken as input-column names, not as result-column names.
    </para>
1161 1162 1163 1164
   </refsect3>

   <refsect3 id="R3-SQL-UNION-1">
    <refsect3info>
1165
     <date>1998-09-24</date>
1166 1167
    </refsect3info>
    <title>
1168
     UNION/INTERSECT/EXCEPT Clause
1169 1170
    </title>
    <para>
1171 1172
     The <acronym>SQL92</acronym> syntax for UNION/INTERSECT/EXCEPT allows an
     additional CORRESPONDING BY option:
1173 1174 1175 1176 1177 1178 1179 1180
     <synopsis> 
<replaceable class="PARAMETER">table_query</replaceable> UNION [ALL]
    [CORRESPONDING [BY (<replaceable class="PARAMETER">column</replaceable> [,...])]]
    <replaceable class="PARAMETER">table_query</replaceable>
     </synopsis></para>

    <para>
     The CORRESPONDING BY clause is not supported by
1181
     <productname>PostgreSQL</productname>.
1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
    </para>
   </refsect3>
   
  </refsect2>
 </refsect1>
</refentry>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
1192
sgml-omittag:nil
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
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:
1204
-->