]> granicus.if.org Git - postgresql/blob - doc/src/sgml/queries.sgml
A bunch of small doco updates motivated by scanning the comments on
[postgresql] / doc / src / sgml / queries.sgml
1 <!-- $Header: /cvsroot/pgsql/doc/src/sgml/queries.sgml,v 1.12 2001/11/19 03:58:24 tgl Exp $ -->
2
3 <chapter id="queries">
4  <title>Queries</title>
5
6  <para>
7   A <firstterm>query</firstterm> is the process of retrieving or the command
8   to retrieve data from a database.  In SQL the <command>SELECT</command>
9   command is used to specify queries.  The general syntax of the
10   <command>SELECT</command> command is
11 <synopsis>
12 SELECT <replaceable>select_list</replaceable> FROM <replaceable>table_expression</replaceable> <optional><replaceable>sort_specification</replaceable></optional>
13 </synopsis>
14   The following sections describe the details of the select list, the
15   table expression, and the sort specification.  The simplest kind of
16   query has the form
17 <programlisting>
18 SELECT * FROM table1;
19 </programlisting>
20   Assuming that there is a table called table1, this command would
21   retrieve all rows and all columns from table1.  (The method of
22   retrieval depends on the client application.  For example, the
23   <application>psql</application> program will display an ASCII-art
24   table on the screen, client libraries will offer functions to
25   retrieve individual rows and columns.)  The select list
26   specification <literal>*</literal> means all columns that the table
27   expression happens to provide.  A select list can also select a
28   subset of the available columns or even make calculations on the
29   columns before retrieving them; see <xref
30   linkend="queries-select-lists">.  For example, if table1 has columns
31   named a, b, and c (and perhaps others) you can make the following
32   query:
33 <programlisting>
34 SELECT a, b + c FROM table1;
35 </programlisting>
36   (assuming that b and c are of a numeric data type).
37  </para>
38
39  <para>
40   <literal>FROM table1</literal> is a particularly simple kind of
41   table expression.  In general, table expressions can be complex
42   constructs of base tables, joins, and subqueries.  But you can also
43   omit the table expression entirely and use the SELECT command as a
44   calculator:
45 <programlisting>
46 SELECT 3 * 4;
47 </programlisting>
48   This is more useful if the expressions in the select list return
49   varying results.  For example, you could call a function this way.
50 <programlisting>
51 SELECT random();
52 </programlisting>
53  </para>
54
55  <sect1 id="queries-table-expressions">
56   <title>Table Expressions</title>
57
58   <para>
59    A <firstterm>table expression</firstterm> specifies a table.  The
60    table expression contains a FROM clause that is optionally followed
61    by WHERE, GROUP BY, and HAVING clauses.  Trivial table expressions
62    simply refer to a table on disk, a so-called base table, but more
63    complex expressions can be used to modify or combine base tables in
64    various ways.
65   </para>
66
67   <para>
68    The optional WHERE, GROUP BY, and HAVING clauses in the table expression
69    specify a pipeline of successive transformations performed on the
70    table derived in the FROM clause.  The derived table that is produced by
71    all these transformations provides the input rows used to compute output
72    rows as specified by the select list of column value expressions.
73   </para>
74         
75   <sect2 id="queries-from">
76    <title>FROM clause</title>
77  
78    <para>
79     The FROM clause derives a table from one or more other tables
80     given in a comma-separated table reference list.
81 <synopsis>
82 FROM <replaceable>table_reference</replaceable> <optional>, <replaceable>table_reference</replaceable> <optional>, ...</optional></optional>
83 </synopsis>
84
85     A table reference may be a table name or a derived table such as a
86     subquery, a table join, or complex combinations of these.  If more
87     than one table reference is listed in the FROM clause they are
88     cross-joined (see below) to form the derived table that may then
89     be subject to transformations by the WHERE, GROUP BY, and HAVING
90     clauses and is finally the result of the overall table expression.
91    </para>
92
93    <para>
94     When a table reference names a table that is the
95     supertable of a table inheritance hierarchy, the table reference
96     produces rows of not only that table but all of its subtable successors,
97     unless the keyword ONLY precedes the table name.  However, the reference
98     produces only the columns that appear in the named table --- any columns
99     added in subtables are ignored.
100    </para>
101
102    <sect3 id="queries-join">
103     <title>Joined Tables</title>
104
105     <indexterm zone="queries-join">
106      <primary>joins</primary>
107     </indexterm>
108
109     <para>
110      A joined table is a table derived from two other (real or
111      derived) tables according to the rules of the particular join
112      type.  INNER, OUTER, and CROSS JOIN are supported.
113     </para>
114
115     <variablelist>
116      <title>Join Types</title>
117
118      <varlistentry>
119       <term>CROSS JOIN</term>
120
121       <indexterm>
122        <primary>joins</primary>
123        <secondary>cross</secondary>
124       </indexterm>
125
126       <listitem>
127 <synopsis>
128 <replaceable>T1</replaceable> CROSS JOIN <replaceable>T2</replaceable>
129 </synopsis>
130
131        <para>
132         For each combination of rows from
133         <replaceable>T1</replaceable> and
134         <replaceable>T2</replaceable>, the derived table will contain a
135         row consisting of all columns in <replaceable>T1</replaceable>
136         followed by all columns in <replaceable>T2</replaceable>.  If
137         the tables have N and M rows respectively, the joined
138         table will have N * M rows.  A cross join is equivalent to an
139         <literal>INNER JOIN ON TRUE</literal>.
140        </para>
141
142        <tip>
143         <para>
144          <literal>FROM <replaceable>T1</replaceable> CROSS JOIN
145          <replaceable>T2</replaceable></literal> is equivalent to
146          <literal>FROM <replaceable>T1</replaceable>,
147          <replaceable>T2</replaceable></literal>.
148         </para>
149        </tip>
150       </listitem>
151      </varlistentry>
152
153      <varlistentry>
154       <term>Qualified joins</term>
155
156       <indexterm>
157        <primary>joins</primary>
158        <secondary>outer</secondary>
159       </indexterm>
160
161       <listitem>
162 <synopsis>
163 <replaceable>T1</replaceable> { <optional>INNER</optional> | { LEFT | RIGHT | FULL } <optional>OUTER</optional> } JOIN <replaceable>T2</replaceable> ON <replaceable>boolean_expression</replaceable>
164 <replaceable>T1</replaceable> { <optional>INNER</optional> | { LEFT | RIGHT | FULL } <optional>OUTER</optional> } JOIN <replaceable>T2</replaceable> USING ( <replaceable>join column list</replaceable> )
165 <replaceable>T1</replaceable> NATURAL { <optional>INNER</optional> | { LEFT | RIGHT | FULL } <optional>OUTER</optional> } JOIN <replaceable>T2</replaceable>
166 </synopsis>
167         
168        <para>
169         The words <token>INNER</token> and <token>OUTER</token> are
170         optional for all joins.  <token>INNER</token> is the default;
171         <token>LEFT</token>, <token>RIGHT</token>, and
172         <token>FULL</token> imply an OUTER JOIN.
173        </para>
174
175        <para>
176         The <firstterm>join condition</firstterm> is specified in the
177         ON or USING clause, or implicitly by the word NATURAL.  The join
178         condition determines which rows from the two source tables are
179         considered to <quote>match</quote>, as explained in detail below.
180        </para>
181
182        <para>
183         The ON clause is the most general kind of join condition: it takes a
184         Boolean value expression of the same kind as is used in a WHERE
185         clause.  A pair of rows from T1 and T2 match if the ON expression
186         evaluates to TRUE for them.
187        </para>
188
189        <para>
190         USING is a shorthand notation: it takes a
191         comma-separated list of column names, which the joined tables
192         must have in common, and forms a join condition specifying equality
193         of each of these pairs of columns.  Furthermore, the output of
194         a JOIN USING has one column for each of the equated pairs of
195         input columns, followed by all of the other columns from each table.
196         Thus, <literal>USING (a, b, c)</literal> is equivalent to
197         <literal>ON (t1.a = t2.a AND t1.b = t2.b AND t1.c = t2.c)</literal>
198         with the exception that
199         if ON is used there will be two columns a, b, and c in the
200         result, whereas with USING there will be only one of each.
201        </para>
202
203        <para>
204         <indexterm>
205          <primary>joins</primary>
206          <secondary>natural</secondary>
207         </indexterm>
208         Finally, NATURAL is a shorthand form of USING: it forms a USING
209         list consisting of exactly those column names that appear in both
210         input tables.  As with USING, these columns appear only once in
211         the output table.
212        </para>
213
214        <para>
215         The possible types of qualified JOIN are:
216        </para>
217
218        <variablelist>
219         <varlistentry>
220          <term>INNER JOIN</term>
221
222          <listitem>
223           <para>
224            For each row R1 of T1, the joined table has a row for each
225            row in T2 that satisfies the join condition with R1.
226           </para>
227          </listitem>
228         </varlistentry>
229
230         <varlistentry>
231          <term>LEFT OUTER JOIN</term>
232
233          <indexterm>
234           <primary>joins</primary>
235           <secondary>left</secondary>
236          </indexterm>
237
238          <listitem>
239           <para>
240            First, an INNER JOIN is performed.  Then, for each row in T1
241            that does not satisfy the join condition with any row in
242            T2, a joined row is returned with NULL values in columns of
243            T2.  Thus, the joined table unconditionally has at least one
244            row for each row in T1.
245           </para>
246          </listitem>
247         </varlistentry>
248          
249         <varlistentry>
250          <term>RIGHT OUTER JOIN</term>
251
252          <listitem>
253           <para>
254            First, an INNER JOIN is performed.  Then, for each row in T2
255            that does not satisfy the join condition with any row in
256            T1, a joined row is returned with NULL values in columns of
257            T1.  This is the converse of a left join: the result table will
258            unconditionally have a row for each row in T2.
259           </para>
260          </listitem>
261         </varlistentry>
262          
263         <varlistentry>
264          <term>FULL OUTER JOIN</term>
265
266          <listitem>
267           <para>
268            First, an INNER JOIN is performed.  Then, for each row in
269            T1 that does not satisfy the join condition with any row in
270            T2, a joined row is returned with null values in columns of
271            T2.  Also, for each row of T2 that does not satisfy the
272            join condition with any row in T1, a joined row with null
273            values in the columns of T1 is returned.
274           </para>
275          </listitem>
276         </varlistentry>
277        </variablelist>
278       </listitem>
279      </varlistentry>
280     </variablelist>
281
282     <para>
283      Joins of all types can be chained together or nested: either
284      or both of <replaceable>T1</replaceable> and
285      <replaceable>T2</replaceable> may be joined tables.  Parentheses
286      may be used around JOIN clauses to control the join order.  In the
287      absence of parentheses, JOIN clauses nest left-to-right.
288     </para>
289    </sect3>
290
291    <sect3 id="queries-subqueries">
292     <title>Subqueries</title>
293
294     <indexterm zone="queries-subqueries">
295      <primary>subqueries</primary>
296     </indexterm>
297
298     <para>
299      Subqueries specifying a derived table must be enclosed in
300      parentheses and <emphasis>must</emphasis> be named using an AS
301      clause.  (See <xref linkend="queries-table-aliases">.)
302     </para>
303
304 <programlisting>
305 FROM (SELECT * FROM table1) AS alias_name
306 </programlisting>
307
308     <para>
309      This example is equivalent to <literal>FROM table1 AS
310      alias_name</literal>.  More interesting cases, which can't be
311      reduced to a plain join, arise when the subquery involves grouping
312      or aggregation.
313     </para>
314    </sect3>
315
316    <sect3 id="queries-table-aliases">
317     <title>Table and Column Aliases</title>
318
319     <indexterm zone="queries-table-aliases">
320      <primary>label</primary>
321      <secondary>table</secondary>
322     </indexterm>
323
324     <indexterm>
325      <primary>alias</primary>
326      <see>label</see>
327     </indexterm>
328
329     <para>
330      A temporary name can be given to tables and complex table
331      references to be used for references to the derived table in
332      further processing.  This is called a <firstterm>table
333      alias</firstterm>.
334 <synopsis>
335 FROM <replaceable>table_reference</replaceable> AS <replaceable>alias</replaceable>
336 </synopsis>
337      Here, <replaceable>alias</replaceable> can be any regular
338      identifier.  The alias becomes the new name of the table
339      reference for the current query -- it is no longer possible to
340      refer to the table by the original name.  Thus
341 <programlisting>
342 SELECT * FROM my_table AS m WHERE my_table.a > 5;
343 </programlisting>
344      is not valid SQL syntax.  What will actually happen (this is a
345      <productname>Postgres</productname> extension to the standard)
346      is that an implicit
347      table reference is added to the FROM clause, so the query is
348      processed as if it were written as
349 <programlisting>
350 SELECT * FROM my_table AS m, my_table AS my_table WHERE my_table.a > 5;
351 </programlisting>
352      Table aliases are mainly for notational convenience, but it is
353      necessary to use them when joining a table to itself, e.g.,
354 <programlisting>
355 SELECT * FROM my_table AS a CROSS JOIN my_table AS b ...
356 </programlisting>
357      Additionally, an alias is required if the table reference is a
358      subquery.
359     </para>
360
361     <para>
362      Parentheses are used to resolve ambiguities.  The following
363      statement will assign the alias <literal>b</literal> to the
364      result of the join, unlike the previous example:
365 <programlisting>
366 SELECT * FROM (my_table AS a CROSS JOIN my_table) AS b ...
367 </programlisting>
368     </para>
369
370     <para>
371 <synopsis>
372 FROM <replaceable>table_reference</replaceable> <replaceable>alias</replaceable>
373 </synopsis>
374      This form is equivalent to the previously treated one; the
375      <token>AS</token> key word is noise.
376     </para>
377
378     <para>
379 <synopsis>
380 FROM <replaceable>table_reference</replaceable> <optional>AS</optional> <replaceable>alias</replaceable> ( <replaceable>column1</replaceable> <optional>, <replaceable>column2</replaceable> <optional>, ...</optional></optional> )
381 </synopsis>
382      In this form,
383      in addition to renaming the table as described above, the columns
384      of the table are also given temporary names for use by the surrounding
385      query.  If fewer column 
386      aliases are specified than the actual table has columns, the remaining
387      columns are not renamed.  This syntax is especially useful for
388      self-joins or subqueries.
389     </para>
390
391     <para>
392      When an alias is applied to the output of a JOIN clause, using any of
393      these forms, the alias hides the original names within the JOIN.
394      For example,
395 <programlisting>
396 SELECT a.* FROM my_table AS a JOIN your_table AS b ON ...
397 </programlisting>
398      is valid SQL, but
399 <programlisting>
400 SELECT a.* FROM (my_table AS a JOIN your_table AS b ON ...) AS c
401 </programlisting>
402      is not valid: the table alias A is not visible outside the alias C.
403     </para>
404    </sect3>
405
406    <sect3 id="queries-table-expression-examples">
407     <title>Examples</title>
408
409     <para>
410 <programlisting>
411 FROM T1 INNER JOIN T2 USING (C)
412 FROM T1 LEFT OUTER JOIN T2 USING (C)
413 FROM (T1 RIGHT OUTER JOIN T2 ON (T1.C1=T2.C1)) AS DT1
414 FROM (T1 FULL OUTER JOIN T2 USING (C)) AS DT1 (DT1C1, DT1C2)
415
416 FROM T1 NATURAL INNER JOIN T2
417 FROM T1 NATURAL LEFT OUTER JOIN T2
418 FROM T1 NATURAL RIGHT OUTER JOIN T2
419 FROM T1 NATURAL FULL OUTER JOIN T2
420
421 FROM (SELECT * FROM T1) DT1 CROSS JOIN T2, T3
422 FROM (SELECT * FROM T1) DT1, T2, T3
423 </programlisting>
424
425      Above are some examples of joined tables and complex derived
426      tables.  Notice how the AS clause renames or names a derived
427      table and how the optional comma-separated list of column names
428      that follows renames the columns.  The last two
429      FROM clauses produce the same derived table from T1, T2, and T3.
430      The AS keyword was omitted in naming the subquery as DT1.  The
431      keywords OUTER and INNER are noise that can be omitted also.
432     </para>
433    </sect3>
434
435   </sect2>
436
437   <sect2 id="queries-where">
438    <title>WHERE clause</title>
439
440    <indexterm zone="queries-where">
441     <primary>where</primary>
442    </indexterm>
443
444    <para>
445     The syntax of the WHERE clause is
446 <synopsis>
447 WHERE <replaceable>search_condition</replaceable>
448 </synopsis>
449     where <replaceable>search_condition</replaceable> is any value
450     expression as defined in <xref linkend="sql-expressions"> that
451     returns a value of type <type>boolean</type>.
452    </para>
453
454    <para>
455     After the processing of the FROM clause is done, each row of the
456     derived table is checked against the search condition.  If the
457     result of the condition is true, the row is kept in the output
458     table, otherwise (that is, if the result is false or NULL) it is
459     discarded.  The search condition typically references at least some
460     column in the table generated in the FROM clause; this is not
461     required, but otherwise the WHERE clause will be fairly useless.
462    </para>
463
464    <note>
465     <para>
466      Before the implementation of the JOIN syntax, it was necessary to
467      put the join condition of an inner join in the WHERE clause.  For
468      example, these table expressions are equivalent:
469 <programlisting>
470 FROM a, b WHERE a.id = b.id AND b.val &gt; 5
471 </programlisting>
472      and
473 <programlisting>
474 FROM a INNER JOIN b ON (a.id = b.id) WHERE b.val &gt; 5
475 </programlisting>
476      or perhaps even
477 <programlisting>
478 FROM a NATURAL JOIN b WHERE b.val &gt; 5
479 </programlisting>
480      Which one of these you use is mainly a matter of style.  The JOIN
481      syntax in the FROM clause is probably not as portable to other
482      products.  For outer joins there is no choice in any case:  they
483      must be done in the FROM clause.  A ON/USING clause of an outer join
484      is <emphasis>not</> equivalent to a WHERE condition, because it
485      determines the addition of rows (for unmatched input rows) as well
486      as the removal of rows from the final result.
487     </para>
488    </note>
489
490 <programlisting>
491 FROM FDT WHERE
492     C1 > 5
493
494 FROM FDT WHERE
495     C1 IN (1, 2, 3)
496 FROM FDT WHERE
497     C1 IN (SELECT C1 FROM T2)
498 FROM FDT WHERE
499     C1 IN (SELECT C3 FROM T2 WHERE C2 = FDT.C1 + 10)
500
501 FROM FDT WHERE
502     C1 BETWEEN (SELECT C3 FROM T2 WHERE C2 = FDT.C1 + 10) AND 100
503
504 FROM FDT WHERE
505     EXISTS (SELECT C1 FROM T2 WHERE C2 > FDT.C1)
506 </programlisting>
507
508    <para>
509     In the examples above, <literal>FDT</literal> is the table derived
510     in the FROM clause. Rows that do not meet the search condition of
511     the where clause are eliminated from
512     <literal>FDT</literal>. Notice the use of scalar subqueries as
513     value expressions.  Just like any other query, the subqueries can
514     employ complex table expressions.  Notice how
515     <literal>FDT</literal> is referenced in the subqueries.
516     Qualifying <literal>C1</> as <literal>FDT.C1</> is only necessary
517     if <literal>C1</> is also the name of a column in the derived
518     input table of the subquery.  Qualifying the column name adds
519     clarity even when it is not needed.  This shows how the column
520     naming scope of an outer query extends into its inner queries.
521    </para>
522   </sect2>
523
524
525   <sect2 id="queries-group">
526    <title>GROUP BY and HAVING clauses</title>      
527
528    <indexterm zone="queries-group">
529     <primary>group</primary>
530    </indexterm>
531
532    <para>
533     After passing the WHERE filter, the derived input table may be
534     subject to grouping, using the GROUP BY clause, and elimination of
535     group rows using the HAVING clause.
536    </para>
537
538 <synopsis>
539 SELECT <replaceable>select_list</replaceable>
540     FROM ...
541     <optional>WHERE ...</optional>
542     GROUP BY <replaceable>grouping_column_reference</replaceable> <optional>, <replaceable>grouping_column_reference</replaceable></optional>...
543 </synopsis>
544
545    <para>
546     The GROUP BY clause is used to group together rows in a table that
547     share the same values in all the columns listed. The order in
548     which the columns are listed does not matter (as opposed to an
549     ORDER BY clause).  The purpose is to reduce each group of rows
550     sharing common values into one group row that is representative of
551     all rows in the group.  This is done to eliminate redundancy in
552     the output and/or obtain aggregates that apply to these groups.
553    </para>
554           
555    <para>
556     Once a table is grouped, columns that are not used in the
557     grouping cannot be referenced except in aggregate expressions,
558     since a specific value in those columns is ambiguous - which row
559     in the group should it come from?  The grouped-by columns can be
560     referenced in select list column expressions since they have a
561     known constant value per group.  Aggregate functions on the
562     ungrouped columns provide values that span the rows of a group,
563     not of the whole table.  For instance, a
564     <function>sum(sales)</function> on a table grouped by product code
565     gives the total sales for each product, not the total sales on all
566     products.  Aggregates computed on the ungrouped columns are
567     representative of the group, whereas individual values of an ungrouped
568     column are not.
569    </para>
570
571    <para>
572     Example:
573 <programlisting>
574 SELECT pid, p.name, (sum(s.units) * p.price) AS sales
575   FROM products p LEFT JOIN sales s USING ( pid )
576   GROUP BY pid, p.name, p.price;
577 </programlisting>
578     In this example, the columns <literal>pid</literal>, <literal>p.name</literal>, and <literal>p.price</literal> must be in
579     the GROUP BY clause since they are referenced in the query select
580     list.  The column s.units does not have to be in the GROUP BY list
581     since it is only used in an aggregate expression
582     (<function>sum()</function>), which represents the group of sales
583     of a product.  For each product, a summary row is returned about
584     all sales of the product.
585    </para>
586
587    <para>
588     In strict SQL, GROUP BY can only group by columns of the source
589     table but Postgres extends this to also allow GROUP BY to group by
590     select columns in the query select list.  Grouping by value
591     expressions instead of simple column names is also allowed.
592    </para>
593
594    <para>
595 <synopsis>
596 SELECT <replaceable>select_list</replaceable> FROM ... <optional>WHERE ...</optional> GROUP BY ... HAVING <replaceable>boolean_expression</replaceable>
597 </synopsis>
598     If a table has been grouped using a GROUP BY clause, but then only
599     certain groups are of interest, the HAVING clause can be used,
600     much like a WHERE clause, to eliminate groups from a grouped
601     table.  Postgres allows a HAVING clause to be
602     used without a GROUP BY, in which case it acts like another WHERE
603     clause, but the point in using HAVING that way is not clear.  A good
604     rule of thumb is that a HAVING condition should refer to the results
605     of aggregate functions.  A restriction that does not involve an
606     aggregate is more efficiently expressed in the WHERE clause.
607    </para>
608
609    <para>
610     Example:
611 <programlisting>
612 SELECT pid    AS "Products",
613        p.name AS "Over 5000",
614        (sum(s.units) * (p.price - p.cost)) AS "Past Month Profit"
615   FROM products p LEFT JOIN sales s USING ( pid )
616   WHERE s.date > CURRENT_DATE - INTERVAL '4 weeks'
617   GROUP BY pid, p.name, p.price, p.cost
618     HAVING sum(p.price * s.units) > 5000;
619 </programlisting>
620     In the example above, the WHERE clause is selecting rows by a
621     column that is not grouped, while the HAVING clause
622     restricts the output to groups with total gross sales over 5000.
623    </para>
624   </sect2>
625  </sect1>
626
627
628  <sect1 id="queries-select-lists">
629   <title>Select Lists</title>
630
631   <indexterm>
632    <primary>select</primary>
633    <secondary>select list</secondary>
634   </indexterm>
635
636   <para>
637    As shown in the previous section,
638    the table expression in the <command>SELECT</command> command
639    constructs an intermediate virtual table by possibly combining
640    tables, views, eliminating rows, grouping, etc.  This table is
641    finally passed on to processing by the <firstterm>select list</firstterm>.  The select
642    list determines which <emphasis>columns</emphasis> of the
643    intermediate table are actually output.  The simplest kind of select list
644    is <literal>*</literal> which emits all columns that the table
645    expression produces.  Otherwise, a select list is a comma-separated
646    list of value expressions (as defined in <xref
647    linkend="sql-expressions">).  For instance, it could be a list of
648    column names:
649 <programlisting>
650 SELECT a, b, c FROM ...
651 </programlisting>
652    The columns names a, b, and c are either the actual names of the
653    columns of tables referenced in the FROM clause, or the aliases
654    given to them as explained in <xref linkend="queries-table-aliases">.
655    The name space available in the select list is the same as in the
656    WHERE clause (unless grouping is used, in which case it is the same
657    as in the HAVING clause).  If more than one table has a column of
658    the same name, the table name must also be given, as in
659 <programlisting>
660 SELECT tbl1.a, tbl2.b, tbl1.c FROM ...
661 </programlisting>
662    (see also <xref linkend="queries-where">).
663   </para>
664
665   <para>
666    If an arbitrary value expression is used in the select list, it
667    conceptually adds a new virtual column to the returned table.  The
668    value expression is evaluated once for each retrieved
669    row, with the row's values substituted for any column references.  But
670    the expressions in the select list do not have to reference any
671    columns in the table expression of the FROM clause; they could be
672    constant arithmetic expressions as well, for instance.
673   </para>
674
675   <sect2 id="queries-column-labels">
676    <title>Column Labels</title>
677
678    <indexterm zone="queries-column-labels">
679     <primary>label</primary>
680     <secondary>column</secondary>
681    </indexterm>
682
683    <para>
684     The entries in the select list can be assigned names for further
685     processing.  The <quote>further processing</quote> in this case is
686     an optional sort specification and the client application (e.g.,
687     column headers for display).  For example:
688 <programlisting>
689 SELECT a AS value, b + c AS sum FROM ...
690 </programlisting>
691    </para>
692
693    <para>
694     If no output column name is specified via AS, the system assigns a
695     default name.  For simple column references, this is the name of the
696     referenced column.  For function 
697     calls, this is the name of the function.  For complex expressions,
698     the system will generate a generic name.
699    </para>
700
701    <note>
702     <para>
703      The naming of output columns here is different from that done in
704      the FROM clause (see <xref linkend="queries-table-aliases">).  This
705      pipeline will in fact allow you to rename the same column twice,
706      but the name chosen in the select list is the one that will be
707      passed on.
708     </para>
709    </note>
710   </sect2>
711
712   <sect2 id="queries-distinct">
713    <title>DISTINCT</title>
714
715    <indexterm zone="queries-distinct">
716     <primary>distinct</primary>
717    </indexterm>
718
719    <para>
720     After the select list has been processed, the result table may
721     optionally be subject to the elimination of duplicates.  The
722     <token>DISTINCT</token> key word is written directly after the
723     <token>SELECT</token> to enable this:
724 <synopsis>
725 SELECT DISTINCT <replaceable>select_list</replaceable> ...
726 </synopsis>
727     (Instead of <token>DISTINCT</token> the word <token>ALL</token>
728     can be used to select the default behavior of retaining all rows.)
729    </para>
730
731    <para>
732     Obviously, two rows are considered distinct if they differ in at
733     least one column value.  NULLs are considered equal in this
734     comparison.
735    </para>
736
737    <para>
738     Alternatively, an arbitrary expression can determine what rows are
739     to be considered distinct:
740 <synopsis>
741 SELECT DISTINCT ON (<replaceable>expression</replaceable> <optional>, <replaceable>expression</replaceable> ...</optional>) <replaceable>select_list</replaceable> ...
742 </synopsis>
743     Here <replaceable>expression</replaceable> is an arbitrary value
744     expression that is evaluated for all rows.  A set of rows for
745     which all the expressions are equal are considered duplicates, and
746     only the first row of the set is kept in the output.  Note that the
747     <quote>first row</quote> of a set is unpredictable unless the
748     query is sorted on enough columns to guarantee a unique ordering
749     of the rows arriving at the DISTINCT filter.  (DISTINCT ON processing
750     occurs after ORDER BY sorting.)
751    </para>
752
753    <para>
754     The DISTINCT ON clause is not part of the SQL standard and is
755     sometimes considered bad style because of the potentially indeterminate
756     nature 
757     of its results.  With judicious use of GROUP BY and subselects in
758     FROM the construct can be avoided, but it is very often the most
759     convenient alternative.
760    </para>
761   </sect2>
762  </sect1>
763
764  <sect1 id="queries-union">
765   <title>Combining Queries</title>
766
767   <indexterm zone="queries-union">
768    <primary>union</primary>
769   </indexterm>
770   <indexterm zone="queries-union">
771    <primary>intersection</primary>
772   </indexterm>
773   <indexterm zone="queries-union">
774    <primary>except</primary>
775   </indexterm>
776
777   <para>
778    The results of two queries can be combined using the set operations
779    union, intersection, and difference.  The syntax is
780 <synopsis>
781 <replaceable>query1</replaceable> UNION <optional>ALL</optional> <replaceable>query2</replaceable>
782 <replaceable>query1</replaceable> INTERSECT <optional>ALL</optional> <replaceable>query2</replaceable>
783 <replaceable>query1</replaceable> EXCEPT <optional>ALL</optional> <replaceable>query2</replaceable>
784 </synopsis>
785    <replaceable>query1</replaceable> and
786    <replaceable>query2</replaceable> are queries that can use any of
787    the features discussed up to this point.  Set operations can also
788    be nested and chained, for example
789 <synopsis>
790 <replaceable>query1</replaceable> UNION <replaceable>query2</replaceable> UNION <replaceable>query3</replaceable>
791 </synopsis>
792    which really says
793 <synopsis>
794 (<replaceable>query1</replaceable> UNION <replaceable>query2</replaceable>) UNION <replaceable>query3</replaceable>
795 </synopsis>
796   </para>
797
798   <para>
799    <command>UNION</command> effectively appends the result of
800    <replaceable>query2</replaceable> to the result of
801    <replaceable>query1</replaceable> (although there is no guarantee
802    that this is the order in which the rows are actually returned).
803    Furthermore, it eliminates all duplicate rows, in the sense of DISTINCT,
804    unless ALL is specified.
805   </para>
806
807   <para>
808    <command>INTERSECT</command> returns all rows that are both in the
809    result of <replaceable>query1</replaceable> and in the result of
810    <replaceable>query2</replaceable>.  Duplicate rows are eliminated
811    unless ALL is specified.
812   </para>
813
814   <para>
815    <command>EXCEPT</command> returns all rows that are in the result
816    of <replaceable>query1</replaceable> but not in the result of
817    <replaceable>query2</replaceable>.  Again, duplicates are
818    eliminated unless ALL is specified.
819   </para>
820
821   <para>
822    In order to calculate the union, intersection, or difference of two
823    queries, the two queries must be <quote>union compatible</quote>,
824    which means that they both return the same number of columns, and
825    that the corresponding columns have compatible data types, as
826    described in <xref linkend="typeconv-union-case">.
827   </para>
828  </sect1>
829
830
831  <sect1 id="queries-order">
832   <title>Sorting Rows</title>
833
834   <indexterm zone="queries-order">
835    <primary>sorting</primary>
836    <secondary>query results</secondary>
837   </indexterm>
838            
839   <para>
840    After a query has produced an output table (after the select list
841    has been processed) it can optionally be sorted.  If sorting is not
842    chosen, the rows will be returned in random order.  The actual
843    order in that case will depend on the scan and join plan types and
844    the order on disk, but it must not be relied on.  A particular
845    output ordering can only be guaranteed if the sort step is explicitly
846    chosen.
847   </para>
848
849   <para>
850    The ORDER BY clause specifies the sort order:
851 <synopsis>
852 SELECT <replaceable>select_list</replaceable>
853     FROM <replaceable>table_expression</replaceable>
854     ORDER BY <replaceable>column1</replaceable> <optional>ASC | DESC</optional> <optional>, <replaceable>column2</replaceable> <optional>ASC | DESC</optional> ...</optional>
855 </synopsis>
856    <replaceable>column1</replaceable>, etc., refer to select list
857    columns.  These can be either the output name of a column (see
858    <xref linkend="queries-column-labels">) or the number of a column.  Some
859    examples:
860 <programlisting>
861 SELECT a, b FROM table1 ORDER BY a;
862 SELECT a + b AS sum, c FROM table1 ORDER BY sum;
863 SELECT a, sum(b) FROM table1 GROUP BY a ORDER BY 1;
864 </programlisting>
865   </para>
866
867   <para>
868    As an extension to the SQL standard, Postgres also allows ordering
869    by arbitrary expressions:
870 <programlisting>
871 SELECT a, b FROM table1 ORDER BY a + b;
872 </programlisting>
873    References to column names in the FROM clause that are renamed in
874    the select list are also allowed:
875 <programlisting>
876 SELECT a AS b FROM table1 ORDER BY a;
877 </programlisting>
878    But these extensions do not work in queries involving UNION, INTERSECT,
879    or EXCEPT, and are not portable to other <acronym>DBMS</acronym>.
880   </para>
881
882   <para>
883    Each column specification may be followed by an optional <token>ASC</token> or
884    <token>DESC</token> to set the sort direction.  <token>ASC</token> is default.  Ascending order
885    puts smaller values first, where <quote>smaller</quote> is defined
886    in terms of the <literal>&lt;</literal> operator.  Similarly,
887    descending order is determined with the <literal>&gt;</literal>
888    operator.
889   </para>
890
891   <para>
892    If more than one sort column is specified, the later entries are
893    used to sort rows that are equal under the order imposed by the
894    earlier sort specifications.
895   </para>
896  </sect1>
897
898  <sect1 id="queries-limit">
899   <title>LIMIT and OFFSET</title>
900
901   <indexterm zone="queries-limit">
902    <primary>limit</primary>
903   </indexterm>
904
905   <indexterm zone="queries-limit">
906    <primary>offset</primary>
907    <secondary>with query results</secondary>
908   </indexterm>
909
910 <synopsis>
911 SELECT <replaceable>select_list</replaceable>
912     FROM <replaceable>table_expression</replaceable>
913     <optional>LIMIT { <replaceable>number</replaceable> | ALL }</optional> <optional>OFFSET <replaceable>number</replaceable></optional>
914 </synopsis>
915
916   <para>
917    LIMIT allows you to retrieve just a portion of the rows that are
918    generated by the rest of the query.  If a limit count is given, no
919    more than that many rows will be returned.
920    LIMIT ALL is the same as omitting a LIMIT clause.
921   </para>
922
923   <para>
924    OFFSET says to skip that many rows before beginning to return rows
925    to the client.  OFFSET 0 is the same as omitting an OFFSET clause.
926    If both OFFSET and LIMIT appear, then OFFSET rows are skipped before
927    starting to count the LIMIT rows that are returned.
928   </para>
929
930   <para>
931    When using LIMIT, it is a good idea to use an ORDER BY clause that
932    constrains the result rows into a unique order.  Otherwise you will
933    get an unpredictable subset of the query's rows---you may be asking
934    for the tenth through twentieth rows, but tenth through twentieth
935    in what ordering?  The ordering is unknown, unless you specified
936    ORDER BY.
937   </para>
938
939   <para>
940    The query optimizer takes LIMIT into account when generating a
941    query plan, so you are very likely to get different plans (yielding
942    different row orders) depending on what you give for LIMIT and
943    OFFSET.  Thus, using different LIMIT/OFFSET values to select
944    different subsets of a query result <emphasis>will give
945    inconsistent results</emphasis> unless you enforce a predictable
946    result ordering with ORDER BY.  This is not a bug; it is an
947    inherent consequence of the fact that SQL does not promise to
948    deliver the results of a query in any particular order unless ORDER
949    BY is used to constrain the order.
950   </para>
951  </sect1>
952
953 </chapter>