select.sgml 26.2 KB
Newer Older
1
<!--
2
$Header: /cvsroot/pgsql/doc/src/sgml/ref/select.sgml,v 1.26 2000/03/15 23:31:19 tgl Exp $
3 4 5
Postgres documentation
-->

6 7
<refentry id="SQL-SELECT">
 <refmeta>
8
  <refentrytitle id="sql-select-title">
9
   SELECT
10 11 12 13 14
  </refentrytitle>
  <refmiscinfo>SQL - Language Statements</refmiscinfo>
 </refmeta>
 <refnamediv>
  <refname>
15
   SELECT
16 17 18 19 20 21
  </refname>
  <refpurpose>
   Retrieve rows from a table or view.
  </refpurpose></refnamediv>
 <refsynopsisdiv>
  <refsynopsisdivinfo>
22
   <date>1999-07-20</date>
23 24
  </refsynopsisdivinfo>
  <synopsis>
25
SELECT [ ALL | DISTINCT [ ON ( <replaceable class="PARAMETER">expression</replaceable> [, ...] ) ] ]
26 27 28
    <replaceable class="PARAMETER">expression</replaceable> [ AS <replaceable class="PARAMETER">name</replaceable> ] [, ...]
    [ INTO [ TEMPORARY | TEMP ] [ TABLE ] <replaceable class="PARAMETER">new_table</replaceable> ]
    [ FROM <replaceable class="PARAMETER">table</replaceable> [ <replaceable class="PARAMETER">alias</replaceable> ] [, ...] ]
29 30 31
    [ WHERE <replaceable class="PARAMETER">condition</replaceable> ]
    [ GROUP BY <replaceable class="PARAMETER">column</replaceable> [, ...] ]
    [ HAVING <replaceable class="PARAMETER">condition</replaceable> [, ...] ]
32
    [ { UNION [ ALL ] | INTERSECT | EXCEPT } <replaceable class="PARAMETER">select</replaceable> ]
33 34 35
    [ ORDER BY <replaceable class="PARAMETER">column</replaceable> [ ASC | DESC | USING <replaceable class="PARAMETER">operator</replaceable> ] [, ...] ]
    [ FOR UPDATE [ OF <replaceable class="PARAMETER">class_name</replaceable> [, ...] ] ]
    LIMIT { <replaceable class="PARAMETER">count</replaceable> | ALL } [ { OFFSET | , } <replaceable class="PARAMETER">start</replaceable> ]
36 37 38 39
  </synopsis>
  
  <refsect2 id="R2-SQL-SELECT-1">
   <refsect2info>
40
    <date>2000-03-15</date>
41 42 43 44
   </refsect2info>
   <title>
    Inputs
   </title>
45

46 47 48
   <para>
    <variablelist>
     <varlistentry>
49
      <term><replaceable class="PARAMETER">expression</replaceable></term>
50 51 52 53 54 55 56 57
      <listitem>
       <para>
	The name of a table's column or an expression.
       </para>
      </listitem>
     </varlistentry>
     
     <varlistentry>
58
      <term><replaceable class="PARAMETER">name</replaceable></term>
59 60 61
      <listitem>
       <para>
	Specifies another name for a column or an expression using
62 63 64 65 66 67
	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
	<replaceable class="PARAMETER">name</replaceable>
	cannot be used in the WHERE or HAVING clauses; write out the
	expression instead.
68 69 70 71
       </para>
      </listitem>
     </varlistentry>
     
T
Thomas G. Lockhart 已提交
72
    <varlistentry>
73 74
     <term>TEMPORARY</term>
     <term>TEMP</term>
T
Thomas G. Lockhart 已提交
75 76
     <listitem>
      <para>
77 78
	If TEMPORARY or TEMP is specified,
	the table is created unique to this session, and is
79
	automatically dropped on session exit.
T
Thomas G. Lockhart 已提交
80 81 82
      </para>
     </listitem>
    </varlistentry>
83

84
     <varlistentry>
85
      <term><replaceable class="PARAMETER">new_table</replaceable></term>
86 87 88
      <listitem>
       <para>
	If the INTO TABLE clause is specified, the result of the
89
	query will be stored in a new table with the indicated
90
	name.
T
Thomas G. Lockhart 已提交
91
	The target table (<replaceable class="PARAMETER">new_table</replaceable>) will
92
	be created automatically and must not exist before this command.
T
Thomas G. Lockhart 已提交
93 94
        Refer to <command>SELECT INTO</command> for more information.

95 96 97 98 99 100 101 102 103 104 105
	<note>
	 <para>
	  The <command>CREATE TABLE AS</command> statement will also
	  create a new  table from a select query.
	 </para>
	</note>
       </para>
      </listitem>
     </varlistentry>
     
     <varlistentry>
106
      <term><replaceable class="PARAMETER">table</replaceable></term>
107 108 109 110 111 112 113 114
      <listitem>
       <para>
	The name of an existing table referenced by the FROM clause.
       </para>
      </listitem>
     </varlistentry>
     
     <varlistentry>
115
      <term><replaceable class="PARAMETER">alias</replaceable></term>
116 117 118 119 120 121 122 123 124 125 126
      <listitem>
       <para>
	An alternate name for the preceding
	<replaceable class="PARAMETER">table</replaceable>.
	It is used for brevity or to eliminate ambiguity for joins
	within a single table.
       </para>
      </listitem>
     </varlistentry>
     
     <varlistentry>
127
      <term><replaceable class="PARAMETER">condition</replaceable></term>
128 129 130 131 132 133 134 135 136
      <listitem>
       <para>
	A boolean expression giving a result of true or false.
	See the WHERE clause.
       </para>
      </listitem>
     </varlistentry>
     
     <varlistentry>
137
      <term><replaceable class="PARAMETER">column</replaceable></term>
138 139 140 141 142 143 144 145
      <listitem>
       <para>
	The name of a table's column.
       </para>
      </listitem>
     </varlistentry>
     
     <varlistentry>
146
      <term><replaceable class="PARAMETER">select</replaceable></term>
147 148
      <listitem>
       <para>
149 150
	A select statement with all features except the ORDER BY and
	LIMIT clauses.
151 152 153 154 155 156 157 158 159 160
       </para>
      </listitem>
     </varlistentry>
     
    </variablelist>
   </para>
  </refsect2>
  
  <refsect2 id="R2-SQL-SELECT-2">
   <refsect2info>
161
    <date>1998-09-24</date>
162 163 164 165
   </refsect2info>
   <title>
    Outputs
   </title>
166
   <para>
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188

    <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>
189
   </para>
190 191
  </refsect2>
 </refsynopsisdiv>
192

193 194
 <refsect1 id="R1-SQL-SELECT-1">
  <refsect1info>
195
   <date>2000-03-15</date>
196 197 198 199 200
  </refsect1info>
  <title>
   Description
  </title>
  <para>
201 202
   <command>SELECT</command> will return rows from one or more tables.
   Candidates for selection are rows which satisfy the WHERE condition;
203
   if WHERE is omitted, all rows are candidates.
204
   (See <xref linkend="sql-where" endterm="sql-where-title">.)
205 206
  </para>

207
  <para>
208
   <command>DISTINCT</command> will eliminate duplicate rows from the
209
   result.
210
   <command>ALL</command> (the default) will return all candidate rows,
211 212
   including duplicates.
  </para>
213

214 215 216
  <para>
   <command>DISTINCT ON</command> eliminates rows that match on all the
   specified expressions, keeping only the first row of each set of
217 218 219
   duplicates.  The DISTINCT ON expressions are interpreted using the
   same rules as for ORDER BY items; see below.
   Note that "the first row" of each set is unpredictable
220 221 222 223 224 225 226 227 228 229 230 231 232
   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>

233
  <para>
234
   The GROUP BY clause allows a user to divide a table
235
   into groups of rows that match on one or more values.
236
   (See <xref linkend="sql-groupby" endterm="sql-groupby-title">.)
237 238
  </para>

239
  <para>
240 241
   The HAVING clause allows selection of only those groups of rows
   meeting the specified condition.
242
   (See <xref linkend="sql-having" endterm="sql-having-title">.)
243
  </para>
244 245
   
  <para>
246 247 248
   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.
249
   (See <xref linkend="sql-orderby-title" endterm="sql-orderby-title">.)
250
  </para>
251 252
   
  <para>
253
   The UNION operator allows the result to be the collection of rows
254
   returned by the queries involved.
255
   (See <xref linkend="sql-union" endterm="sql-union-title">.)
256
  </para>
257 258
   
  <para>
259
   The INTERSECT operator gives you the rows that are common to both queries.
260
   (See <xref linkend="sql-intersect" endterm="sql-intersect-title">.)
261
  </para>
262 263
   
  <para>
264 265
   The EXCEPT operator gives you the rows returned by the first query but
   not the second query.
266
   (See <xref linkend="sql-except" endterm="sql-except-title">.)
267
  </para>
268
   
269 270 271
  <para>
   The FOR UPDATE clause allows the SELECT statement to perform 
   exclusive locking of selected rows.
272
  </para>
273 274
   
  <para>
275 276 277
   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">.)
278
  </para>
279

280
  <para>
281
   You must have SELECT privilege to a table to read its values
282 283
   (See the <command>GRANT</command>/<command>REVOKE</command> statements).
  </para>
284
   
285
  <refsect2 id="SQL-WHERE">
286
   <refsect2info>
287
    <date>2000-03-15</date>
288
   </refsect2info>
289
   <title id="sql-where-title">
290
    WHERE Clause
291
   </title>
292

293 294 295 296
   <para>
    The optional WHERE condition has the general form:
    
    <synopsis>
297
WHERE <replaceable class="PARAMETER">boolean_expr</replaceable>
298 299
    </synopsis>
    
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
    <replaceable class="PARAMETER">boolean_expr</replaceable>
    can consist of any expression which evaluates to a boolean value.
    In many cases, this expression will be

    <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
317
    locally-defined operator, 
318 319
    and <replaceable class="PARAMETER">log_op</replaceable> can be one 
    of: AND, OR, NOT.
320 321
    SELECT will ignore all rows for which the WHERE condition does not return
    TRUE.
322 323 324
   </para>
  </refsect2>
  
325
  <refsect2 id="SQL-GROUPBY">
326
   <refsect2info>
327
    <date>2000-03-15</date>
328
   </refsect2info>
329
   <title id="sql-groupby-title">
330
    GROUP BY Clause
331 332
   </title>
   <para>
333
    GROUP BY specifies a grouped table derived by the application
334
    of this clause:
335
    <synopsis>
336
GROUP BY <replaceable class="PARAMETER">column</replaceable> [, ...]
337 338 339 340
    </synopsis>
   </para>

   <para>
341
    GROUP BY will condense into a single row all selected rows that share the
342 343 344 345
    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
346 347
    rows).  When GROUP BY is present, it is not valid for the SELECT
    output expression(s) to refer to
348 349
    ungrouped columns except within aggregate functions, since there
    would be more than one possible value to return for an ungrouped column.
350
   </para>
351 352 353 354 355 356 357

   <para>
    An item in GROUP BY can also 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, a GROUP BY name will
    be interpreted as an input-column name rather than an output column name.
   </para>
358 359
  </refsect2>

360
  <refsect2 id="SQL-HAVING">
361
   <refsect2info>
362
    <date>2000-03-15</date>
363
   </refsect2info>
364
   <title id="sql-having-title">
365
    HAVING Clause
366 367 368 369 370 371 372 373 374
   </title>
   <para>
    The optional HAVING condition has the general form:
    
    <synopsis>
HAVING <replaceable class="PARAMETER">cond_expr</replaceable>
    </synopsis>
    
    where <replaceable class="PARAMETER">cond_expr</replaceable> is the same
375 376
    as specified for the WHERE clause.
   </para>
377 378
    
   <para>
379
    HAVING specifies a grouped table derived by the elimination
380 381 382 383 384 385
    of group rows that do not satisfy the
    <replaceable class="PARAMETER">cond_expr</replaceable>.
    HAVING is different from WHERE:
    WHERE filters individual rows before application of GROUP BY,
    while HAVING filters group rows created by GROUP BY.
   </para>
386

387
   <para>
388
    Each column referenced in 
389
    <replaceable class="PARAMETER">cond_expr</replaceable> shall unambiguously
390 391
    reference a grouping column, unless the reference appears within an
    aggregate function.
392 393 394
   </para>
  </refsect2>
  
395
  <refsect2 id="SQL-ORDERBY">
396
   <refsect2info>
397
    <date>2000-03-15</date>
398
   </refsect2info>
399
   <title id="sql-orderby-title">
400
    ORDER BY Clause
401 402 403
   </title>
   <para>
    <synopsis>
404
ORDER BY <replaceable class="PARAMETER">column</replaceable> [ ASC | DESC ] [, ...]
405 406 407
    </synopsis></para>
    
   <para>
408 409
    <replaceable class="PARAMETER">column</replaceable> can be either a
    result column name or an ordinal number.
410
   </para>
411
   <para>
412
    The ordinal numbers refers to the ordinal (left-to-right) position
413
    of the result column. This feature makes it possible to define an ordering
414
    on the basis of a column that does not have a proper name.
415
    This is never absolutely necessary because it is always possible
416
    to assign a name to a result column using the AS clause, e.g.:
417
    <programlisting>
418
SELECT title, date_prod + 1 AS newlen FROM films ORDER BY newlen;
419 420 421
    </programlisting></para>
    
   <para>
422 423 424
    From release 6.4 of PostgreSQL, it is also possible to ORDER BY
    arbitrary expressions, including fields that do not appear in the
    SELECT result list.
425
    Thus the following statement is now legal:
426
    <programlisting>
427
SELECT name FROM distributors ORDER BY code;
428
    </programlisting>
429 430 431 432 433
    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.
434
   </para>
435 436
    
   <para>
437 438
    Optionally one may add the keyword DESC (descending)
    or ASC (ascending) after each column name in the ORDER BY clause.
439 440 441
    If not specified, ASC is assumed by default.  Alternatively, a
    specific ordering operator name may be specified.  ASC is equivalent
    to USING '&lt;' and DESC is equivalent to USING '&gt;'.
442
   </para>
443 444
  </refsect2>
  
445
  <refsect2 id="SQL-UNION">
446
   <refsect2info>
447
    <date>1998-09-24</date>
448
   </refsect2info>
449
   <title id="sql-union-title">
450
    UNION Clause
451 452 453
   </title>
   <para>
    <synopsis>
454 455
<replaceable class="PARAMETER">table_query</replaceable> UNION [ ALL ] <replaceable class="PARAMETER">table_query</replaceable>
    [ ORDER BY <replaceable class="PARAMETER">column</replaceable> [ ASC | DESC ] [, ...] ]
456
    </synopsis>
457

458 459
    where
    <replaceable class="PARAMETER">table_query</replaceable>
460
    specifies any select expression without an ORDER BY or LIMIT clause.
461
   </para>
462 463
    
   <para>
464 465 466 467
    The UNION operator allows the result to be the collection of rows
    returned by the queries involved.
    The two SELECTs that represent the direct operands of the UNION must
    produce the same number of columns, and corresponding columns must be
468 469
    of compatible data types.
   </para>
470 471 472
    
   <para>
    By default, the result of UNION does not contain any duplicate rows
473 474
    unless the ALL clause is specified.
   </para>
475 476
    
   <para>
477
    Multiple UNION operators in the same SELECT statement are
478
    evaluated left to right.
479
    Note that the ALL keyword is not global in nature, being 
480 481 482
    applied only for the current pair of table results.
   </para>

483 484
  </refsect2>

485
  <refsect2 id="SQL-INTERSECT">
486 487 488
   <refsect2info>
    <date>1998-09-24</date>
   </refsect2info>
489
   <title id="sql-intersect-title">
490 491 492 493
    INTERSECT Clause
   </title>
   <para>
    <synopsis>
494 495
<replaceable class="PARAMETER">table_query</replaceable> INTERSECT <replaceable class="PARAMETER">table_query</replaceable>
    [ ORDER BY <replaceable class="PARAMETER">column</replaceable> [ ASC | DESC ] [, ...] ]
496 497 498 499
    </synopsis>
    
    where
    <replaceable class="PARAMETER">table_query</replaceable>
500
    specifies any select expression without an ORDER BY or LIMIT clause.
501 502
   </para>

503
   <para>
504 505 506
    The INTERSECT operator gives you the rows that are common to both queries.
    The two SELECTs that represent the direct operands of the INTERSECT must
    produce the same number of columns, and corresponding columns must be
507 508
    of compatible data types.
   </para>
509 510 511
    
   <para>
    Multiple INTERSECT operators in the same SELECT statement are
512
    evaluated left to right, unless parentheses dictate otherwise.
513
   </para>
514 515
  </refsect2>

516
  <refsect2 id="SQL-EXCEPT">
517 518 519
   <refsect2info>
    <date>1998-09-24</date>
   </refsect2info>
520
   <title id="sql-except-title">
521 522 523 524
    EXCEPT Clause
   </title>
   <para>
    <synopsis>
525
<replaceable class="PARAMETER">table_query</replaceable> EXCEPT <replaceable class="PARAMETER">table_query</replaceable>
526 527
     [ ORDER BY <replaceable class="PARAMETER">column</replaceable> [ ASC | DESC ] [, ...] ]
    </synopsis>
528
    
529 530
    where
    <replaceable class="PARAMETER">table_query</replaceable>
531
    specifies any select expression without an ORDER BY or LIMIT clause.
532 533
   </para>

534
   <para>
535 536 537 538
    The EXCEPT operator gives you the rows returned by the first query but
    not the second query.
    The two SELECTs that represent the direct operands of the EXCEPT must
    produce the same number of columns, and corresponding columns must be
539 540 541
    of compatible data types.
   </para>

542 543
   <para>
    Multiple EXCEPT operators in the same SELECT statement are
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
    evaluated left to right, unless parentheses dictate otherwise.
   </para>
  </refsect2>

  <refsect2 id="SQL-LIMIT">
   <refsect2info>
    <date>2000-02-20</date>
   </refsect2info>
   <title id="sql-limit-title">
    LIMIT Clause
   </title>
   <para>
    <synopsis>
    LIMIT { <replaceable class="PARAMETER">count</replaceable> | ALL } [ { OFFSET | , } <replaceable class="PARAMETER">start</replaceable> ]
    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
    an unpredictable subset of the query's rows --- you may be asking for
    the tenth through twentieth rows, but tenth through twentieth in what
    ordering?  You don't know what ordering, unless you specified ORDER BY.
   </para>

   <para>
584
    As of PostgreSQL 7.0, the
585 586 587 588 589 590 591 592 593
    query optimizer takes 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 give for LIMIT and OFFSET.  Thus, using
    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.
594
   </para>
595
  </refsect2>
596
 </refsect1>
597

598 599 600 601
 <refsect1 id="R1-SQL-SELECT-2">
  <title>
   Usage
  </title>
602

603 604 605
  <para>
   To join the table <literal>films</literal> with the table
   <literal>distributors</literal>:
606 607

   <programlisting>
608 609 610
SELECT f.title, f.did, d.name, f.date_prod, f.kind
    FROM distributors d, films f
    WHERE f.did = d.did
611

T
Thomas G. Lockhart 已提交
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
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
631 632 633
   </programlisting>
  </para>

634 635
  <para>
   To sum the column <literal>len</literal> of all films and group
636
   the results by <literal>kind</literal>:
637 638

   <programlisting>
639
SELECT kind, SUM(len) AS total FROM films GROUP BY kind;
640 641 642 643 644 645 646 647

    kind      |total
    ----------+------
    Action    | 07:34
    Comedy    | 02:58
    Drama     | 14:28
    Musical   | 06:42
    Romantic  | 04:38
648 649
   </programlisting>
  </para>
650 651 652

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

   <programlisting>
657 658 659 660
SELECT kind, SUM(len) AS total
    FROM films
    GROUP BY kind
    HAVING SUM(len) < INTERVAL '5 hour';
661 662 663 664 665

    kind      |total
    ----------+------
    Comedy    | 02:58
    Romantic  | 04:38
666 667 668
   </programlisting>
  </para>

669
  <para>
670
   The following two examples are identical ways of sorting the individual
671 672
   results according to the contents of the second column
   (<literal>name</literal>):
673 674

   <programlisting>
675 676
SELECT * FROM distributors ORDER BY name;
SELECT * FROM distributors ORDER BY 2;
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692

    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
693 694
   </programlisting>
  </para>
695 696 697 698 699

  <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
700
   with letter W in each table.  Only distinct rows are wanted, so the
701
   ALL keyword is omitted:
702 703

   <programlisting>
704
    --        distributors:                actors:
705 706 707 708 709 710
    --        did|name                     id|name
    --        ---+------------             --+--------------
    --        108|Westward                  1|Woody Allen
    --        111|Walt Disney               2|Warren Beatty
    --        112|Warner Bros.              3|Walter Matthau
    --        ...                           ...
711

712
SELECT distributors.name
713 714
    FROM   distributors
    WHERE  distributors.name LIKE 'W%'
715 716 717 718
UNION
SELECT actors.name
    FROM   actors
    WHERE  actors.name LIKE 'W%'
719

T
Thomas G. Lockhart 已提交
720 721 722 723 724 725 726 727
name
--------------
Walt Disney
Walter Matthau
Warner Bros.
Warren Beatty
Westward
Woody Allen
728 729
   </programlisting>
  </para>
730 731 732 733 734 735 736 737
 </refsect1>
 
 <refsect1 id="R1-SQL-SELECT-3">
  <title>
   Compatibility
  </title>
  
  <refsect2 id="R2-SQL-SELECT-4">
738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756
   <refsect2info>
    <date>1998-09-24</date>
   </refsect2info>
   <title>
    <acronym>Extensions</acronym>
   </title>

   <para>
<productname>Postgres</productname> allows one to omit 
the <command>FROM</command> clause from a query. This feature
was retained from the original PostQuel query language:
  <programlisting>
SELECT distributors.* WHERE name = 'Westwood';

    did|name
    ---+----------------
    108|Westward
  </programlisting>
   </para>
757
  </refsect2>
758 759

  <refsect2 id="R2-SQL-SELECT-5">
760
   <refsect2info>
761
    <date>1998-09-24</date>
762 763 764 765 766 767 768 769 770 771 772 773
   </refsect2info>
   <title>
    <acronym>SQL92</acronym>
   </title>
   <para>
   </para>
   
   <refsect3 id="R3-SQL-SELECT-1">
    <refsect3info>
     <date>1998-04-15</date>
    </refsect3info>
    <title>
774
     SELECT Clause
775 776 777 778 779 780 781 782 783 784
    </title>
    <para>
     In the <acronym>SQL92</acronym> standard, the optional keyword "AS"
     is just noise and can be 
     omitted without affecting the meaning.
     The <productname>Postgres</productname> parser requires this keyword when
     renaming columns because the type extensibility features lead to
     parsing ambiguities
     in this context.</para>
     
785 786
    <para>
     The DISTINCT ON phrase is not part of <acronym>SQL92</acronym>.
787
     Nor are LIMIT and OFFSET.
788
    </para>
789 790 791 792 793 794 795 796 797 798 799 800
     
    <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.
     <productname>Postgres</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>Postgres</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.
    </para>
801 802 803 804
   </refsect3>

   <refsect3 id="R3-SQL-UNION-1">
    <refsect3info>
805
     <date>1998-09-24</date>
806 807
    </refsect3info>
    <title>
808
     UNION Clause
809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831
    </title>
    <para>
     The <acronym>SQL92</acronym> syntax for UNION allows an
     additional CORRESPONDING BY clause:
     <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
     <productname>Postgres</productname>.
    </para>
   </refsect3>
   
  </refsect2>
 </refsect1>
</refentry>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
832
sgml-omittag:nil
833 834 835 836 837 838 839 840 841 842 843
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:
844
-->