]> granicus.if.org Git - postgresql/blob - doc/src/sgml/ref/select.sgml
Add documentation for data-modifying statements in WITH clauses.
[postgresql] / doc / src / sgml / ref / select.sgml
1 <!--
2 doc/src/sgml/ref/select.sgml
3 PostgreSQL documentation
4 -->
5
6 <refentry id="SQL-SELECT">
7  <refmeta>
8   <refentrytitle>SELECT</refentrytitle>
9   <manvolnum>7</manvolnum>
10   <refmiscinfo>SQL - Language Statements</refmiscinfo>
11  </refmeta>
12
13  <refnamediv>
14   <refname>SELECT</refname>
15   <refname>TABLE</refname>
16   <refname>WITH</refname>
17   <refpurpose>retrieve rows from a table or view</refpurpose>
18  </refnamediv>
19
20  <indexterm zone="sql-select">
21   <primary>SELECT</primary>
22  </indexterm>
23
24  <indexterm zone="sql-select">
25   <primary>TABLE command</primary>
26  </indexterm>
27
28  <indexterm zone="sql-select">
29   <primary>WITH</primary>
30   <secondary>in SELECT</secondary>
31  </indexterm>
32
33  <refsynopsisdiv>
34 <synopsis>
35 [ WITH [ RECURSIVE ] <replaceable class="parameter">with_query</replaceable> [, ...] ]
36 SELECT [ ALL | DISTINCT [ ON ( <replaceable class="parameter">expression</replaceable> [, ...] ) ] ]
37     * | <replaceable class="parameter">expression</replaceable> [ [ AS ] <replaceable class="parameter">output_name</replaceable> ] [, ...]
38     [ FROM <replaceable class="parameter">from_item</replaceable> [, ...] ]
39     [ WHERE <replaceable class="parameter">condition</replaceable> ]
40     [ GROUP BY <replaceable class="parameter">expression</replaceable> [, ...] ]
41     [ HAVING <replaceable class="parameter">condition</replaceable> [, ...] ]
42     [ WINDOW <replaceable class="parameter">window_name</replaceable> AS ( <replaceable class="parameter">window_definition</replaceable> ) [, ...] ]
43     [ { UNION | INTERSECT | EXCEPT } [ ALL | DISTINCT ] <replaceable class="parameter">select</replaceable> ]
44     [ ORDER BY <replaceable class="parameter">expression</replaceable> [ ASC | DESC | USING <replaceable class="parameter">operator</replaceable> ] [ NULLS { FIRST | LAST } ] [, ...] ]
45     [ LIMIT { <replaceable class="parameter">count</replaceable> | ALL } ]
46     [ OFFSET <replaceable class="parameter">start</replaceable> [ ROW | ROWS ] ]
47     [ FETCH { FIRST | NEXT } [ <replaceable class="parameter">count</replaceable> ] { ROW | ROWS } ONLY ]
48     [ FOR { UPDATE | SHARE } [ OF <replaceable class="parameter">table_name</replaceable> [, ...] ] [ NOWAIT ] [...] ]
49
50 <phrase>where <replaceable class="parameter">from_item</replaceable> can be one of:</phrase>
51
52     [ ONLY ] <replaceable class="parameter">table_name</replaceable> [ * ] [ [ AS ] <replaceable class="parameter">alias</replaceable> [ ( <replaceable class="parameter">column_alias</replaceable> [, ...] ) ] ]
53     ( <replaceable class="parameter">select</replaceable> ) [ AS ] <replaceable class="parameter">alias</replaceable> [ ( <replaceable class="parameter">column_alias</replaceable> [, ...] ) ]
54     <replaceable class="parameter">with_query_name</replaceable> [ [ AS ] <replaceable class="parameter">alias</replaceable> [ ( <replaceable class="parameter">column_alias</replaceable> [, ...] ) ] ]
55     <replaceable class="parameter">function_name</replaceable> ( [ <replaceable class="parameter">argument</replaceable> [, ...] ] ) [ AS ] <replaceable class="parameter">alias</replaceable> [ ( <replaceable class="parameter">column_alias</replaceable> [, ...] | <replaceable class="parameter">column_definition</replaceable> [, ...] ) ]
56     <replaceable class="parameter">function_name</replaceable> ( [ <replaceable class="parameter">argument</replaceable> [, ...] ] ) AS ( <replaceable class="parameter">column_definition</replaceable> [, ...] )
57     <replaceable class="parameter">from_item</replaceable> [ NATURAL ] <replaceable class="parameter">join_type</replaceable> <replaceable class="parameter">from_item</replaceable> [ ON <replaceable class="parameter">join_condition</replaceable> | USING ( <replaceable class="parameter">join_column</replaceable> [, ...] ) ]
58
59 <phrase>and <replaceable class="parameter">with_query</replaceable> is:</phrase>
60
61     <replaceable class="parameter">with_query_name</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ...] ) ] AS ( <replaceable class="parameter">select</replaceable> | <replaceable class="parameter">insert</replaceable> | <replaceable class="parameter">update</replaceable> | <replaceable class="parameter">delete</replaceable> )
62
63 TABLE [ ONLY ] <replaceable class="parameter">table_name</replaceable> [ * ]
64 </synopsis>
65
66  </refsynopsisdiv>
67
68  <refsect1>
69   <title>Description</title>
70
71   <para>
72    <command>SELECT</command> retrieves rows from zero or more tables.
73    The general processing of <command>SELECT</command> is as follows:
74
75    <orderedlist>
76     <listitem>
77      <para>
78       All queries in the <literal>WITH</literal> list are computed.
79       These effectively serve as temporary tables that can be referenced
80       in the <literal>FROM</literal> list.  A <literal>WITH</literal> query
81       that is referenced more than once in <literal>FROM</literal> is
82       computed only once.
83       (See <xref linkend="sql-with" endterm="sql-with-title"> below.)
84      </para>
85     </listitem>
86
87     <listitem>
88      <para>
89       All elements in the <literal>FROM</literal> list are computed.
90       (Each element in the <literal>FROM</literal> list is a real or
91       virtual table.)  If more than one element is specified in the
92       <literal>FROM</literal> list, they are cross-joined together.
93       (See <xref linkend="sql-from" endterm="sql-from-title"> below.)
94      </para>
95     </listitem>
96
97     <listitem>
98      <para>
99       If the <literal>WHERE</literal> clause is specified, all rows
100       that do not satisfy the condition are eliminated from the
101       output.  (See <xref linkend="sql-where"
102       endterm="sql-where-title"> below.)
103      </para>
104     </listitem>
105
106     <listitem>
107      <para>
108       If the <literal>GROUP BY</literal> clause is specified, the
109       output is combined into groups of rows that match on one or more
110       values.  If the <literal>HAVING</literal> clause is present, it
111       eliminates groups that do not satisfy the given condition.  (See
112       <xref linkend="sql-groupby" endterm="sql-groupby-title"> and
113       <xref linkend="sql-having" endterm="sql-having-title"> below.)
114      </para>
115     </listitem>
116
117     <listitem>
118      <para>
119       The actual output rows are computed using the
120       <command>SELECT</command> output expressions for each selected
121       row or row group.  (See
122       <xref linkend="sql-select-list" endterm="sql-select-list-title">
123       below.)
124      </para>
125     </listitem>
126
127     <listitem>
128      <para>
129       <literal>SELECT DISTINCT</literal> eliminates duplicate rows from the
130       result.  <literal>SELECT DISTINCT ON</literal> eliminates rows that
131       match on all the specified expressions.  <literal>SELECT ALL</literal>
132       (the default) will return all candidate rows, including
133       duplicates.  (See <xref linkend="sql-distinct"
134       endterm="sql-distinct-title"> below.)
135      </para>
136     </listitem>
137
138     <listitem>
139      <para>
140       Using the operators <literal>UNION</literal>,
141       <literal>INTERSECT</literal>, and <literal>EXCEPT</literal>, the
142       output of more than one <command>SELECT</command> statement can
143       be combined to form a single result set.  The
144       <literal>UNION</literal> operator returns all rows that are in
145       one or both of the result sets.  The
146       <literal>INTERSECT</literal> operator returns all rows that are
147       strictly in both result sets.  The <literal>EXCEPT</literal>
148       operator returns the rows that are in the first result set but
149       not in the second.  In all three cases, duplicate rows are
150       eliminated unless <literal>ALL</literal> is specified.  The noise
151       word <literal>DISTINCT</> can be added to explicitly specify
152       eliminating duplicate rows.  Notice that <literal>DISTINCT</> is
153       the default behavior here, even though <literal>ALL</literal> is
154       the default for <command>SELECT</> itself.  (See
155       <xref linkend="sql-union" endterm="sql-union-title">, <xref
156       linkend="sql-intersect" endterm="sql-intersect-title">, and
157       <xref linkend="sql-except" endterm="sql-except-title"> below.)
158      </para>
159     </listitem>
160
161     <listitem>
162      <para>
163       If the <literal>ORDER BY</literal> clause is specified, the
164       returned rows are sorted in the specified order.  If
165       <literal>ORDER BY</literal> is not given, the rows are returned
166       in whatever order the system finds fastest to produce.  (See
167       <xref linkend="sql-orderby" endterm="sql-orderby-title"> below.)
168      </para>
169     </listitem>
170
171     <listitem>
172      <para>
173       If the <literal>LIMIT</literal> (or <literal>FETCH FIRST</literal>) or <literal>OFFSET</literal>
174       clause is specified, the <command>SELECT</command> statement
175       only returns a subset of the result rows. (See <xref
176       linkend="sql-limit" endterm="sql-limit-title"> below.)
177      </para>
178     </listitem>
179
180     <listitem>
181      <para>
182       If <literal>FOR UPDATE</literal> or <literal>FOR SHARE</literal>
183       is specified, the
184       <command>SELECT</command> statement locks the selected rows
185       against concurrent updates.  (See <xref linkend="sql-for-update-share"
186       endterm="sql-for-update-share-title"> below.)
187      </para>
188     </listitem>
189    </orderedlist>
190   </para>
191
192   <para>
193    You must have <literal>SELECT</literal> privilege on each column used
194    in a <command>SELECT</> command.  The use of <literal>FOR UPDATE</literal>
195    or <literal>FOR SHARE</literal> requires
196    <literal>UPDATE</literal> privilege as well (for at least one column
197    of each table so selected).
198   </para>
199  </refsect1>
200
201  <refsect1>
202   <title>Parameters</title>
203
204   <refsect2 id="SQL-WITH">
205    <title id="sql-with-title"><literal>WITH</literal> Clause</title>
206
207    <para>
208     The <literal>WITH</literal> clause allows you to specify one or more
209     subqueries that can be referenced by name in the primary query.
210     The subqueries effectively act as temporary tables or views
211     for the duration of the primary query.
212     Each subquery can be a <command>SELECT</command>,
213     <command>INSERT</command>, <command>UPDATE</command> or
214     <command>DELETE</command> statement.
215     When writing a data-modifying statement (<command>INSERT</command>,
216     <command>UPDATE</command> or <command>DELETE</command>) in
217     <literal>WITH</>, it is usual to include a <literal>RETURNING</> clause.
218     It is the output of <literal>RETURNING</>, <emphasis>not</> the underlying
219     table that the statement modifies, that forms the temporary table that is
220     read by the primary query.  If <literal>RETURNING</> is omitted, the
221     statement is still executed, but it produces no output so it cannot be
222     referenced as a table by the primary query.
223    </para>
224
225    <para>
226     A name (without schema qualification) must be specified for each
227     <literal>WITH</literal> query.  Optionally, a list of column names
228     can be specified; if this is omitted,
229     the column names are inferred from the subquery.
230    </para>
231
232    <para>
233     If <literal>RECURSIVE</literal> is specified, it allows a
234     <command>SELECT</command> subquery to reference itself by name.  Such a
235     subquery must have the form
236 <synopsis>
237 <replaceable class="parameter">non_recursive_term</replaceable> UNION [ ALL | DISTINCT ] <replaceable class="parameter">recursive_term</replaceable>
238 </synopsis>
239     where the recursive self-reference must appear on the right-hand
240     side of the <literal>UNION</>.  Only one recursive self-reference
241     is permitted per query.  Recursive data-modifying statements are not
242     supported, but you can use the results of a recursive
243     <command>SELECT</command> query in
244     a data-modifying statement.  See <xref linkend="queries-with"> for
245     an example.
246    </para>
247
248    <para>
249     Another effect of <literal>RECURSIVE</literal> is that
250     <literal>WITH</literal> queries need not be ordered: a query
251     can reference another one that is later in the list.  (However,
252     circular references, or mutual recursion, are not implemented.)
253     Without <literal>RECURSIVE</literal>, <literal>WITH</literal> queries
254     can only reference sibling <literal>WITH</literal> queries
255     that are earlier in the <literal>WITH</literal> list.
256    </para>
257
258    <para>
259     A key property of <literal>WITH</literal> queries is that they
260     are evaluated only once per execution of the primary query,
261     even if the primary query refers to them more than once.
262     In particular, data-modifying statements are guaranteed to be
263     executed once and only once, regardless of whether the primary query
264     reads all or any of their output.
265    </para>
266
267    <para>
268     The primary query and the <literal>WITH</literal> queries are all
269     (notionally) executed at the same time.  This implies that the effects of
270     a data-modifying statement in <literal>WITH</literal> cannot be seen from
271     other parts of the query, other than by reading its <literal>RETURNING</>
272     output.  If two such data-modifying statements attempt to modify the same
273     row, the results are unspecified.
274    </para>
275
276    <para>
277     See <xref linkend="queries-with"> for additional information.
278    </para>
279   </refsect2>
280
281   <refsect2 id="SQL-FROM">
282    <title id="sql-from-title"><literal>FROM</literal> Clause</title>
283
284    <para>
285     The <literal>FROM</literal> clause specifies one or more source
286     tables for the <command>SELECT</command>.  If multiple sources are
287     specified, the result is the Cartesian product (cross join) of all
288     the sources.  But usually qualification conditions
289     are added to restrict the returned rows to a small subset of the
290     Cartesian product.
291    </para>
292
293    <para>
294     The <literal>FROM</literal> clause can contain the following
295     elements:
296
297     <variablelist>
298      <varlistentry>
299       <term><replaceable class="parameter">table_name</replaceable></term>
300       <listitem>
301        <para>
302         The name (optionally schema-qualified) of an existing table or
303         view.  If <literal>ONLY</> is specified, only that table is
304         scanned.  If <literal>ONLY</> is not specified, the table and
305         any descendant tables are scanned.
306        </para>
307       </listitem>
308      </varlistentry>
309
310      <varlistentry>
311       <term><replaceable class="parameter">alias</replaceable></term>
312       <listitem>
313        <para>
314         A substitute name for the <literal>FROM</> item containing the
315         alias.  An alias is used for brevity or to eliminate ambiguity
316         for self-joins (where the same table is scanned multiple
317         times).  When an alias is provided, it completely hides the
318         actual name of the table or function; for example given
319         <literal>FROM foo AS f</>, the remainder of the
320         <command>SELECT</command> must refer to this <literal>FROM</>
321         item as <literal>f</> not <literal>foo</>.  If an alias is
322         written, a column alias list can also be written to provide
323         substitute names for one or more columns of the table.
324        </para>
325       </listitem>
326      </varlistentry>
327
328      <varlistentry>
329       <term><replaceable class="parameter">select</replaceable></term>
330       <listitem>
331        <para>
332         A sub-<command>SELECT</command> can appear in the
333         <literal>FROM</literal> clause.  This acts as though its
334         output were created as a temporary table for the duration of
335         this single <command>SELECT</command> command.  Note that the
336         sub-<command>SELECT</command> must be surrounded by
337         parentheses, and an alias <emphasis>must</emphasis> be
338         provided for it.  A
339         <xref linkend="sql-values"> command
340         can also be used here.
341        </para>
342       </listitem>
343      </varlistentry>
344
345      <varlistentry>
346       <term><replaceable class="parameter">with_query_name</replaceable></term>
347       <listitem>
348        <para>
349         A <literal>WITH</> query is referenced by writing its name,
350         just as though the query's name were a table name.  (In fact,
351         the <literal>WITH</> query hides any real table of the same name
352         for the purposes of the primary query.  If necessary, you can
353         refer to a real table of the same name by schema-qualifying
354         the table's name.)
355         An alias can be provided in the same way as for a table.
356        </para>
357       </listitem>
358      </varlistentry>
359
360      <varlistentry>
361       <term><replaceable class="parameter">function_name</replaceable></term>
362       <listitem>
363        <para>
364         Function calls can appear in the <literal>FROM</literal>
365         clause.  (This is especially useful for functions that return
366         result sets, but any function can be used.)  This acts as
367         though its output were created as a temporary table for the
368         duration of this single <command>SELECT</command> command. An
369         alias can also be used. If an alias is written, a column alias
370         list can also be written to provide substitute names for one
371         or more attributes of the function's composite return type. If
372         the function has been defined as returning the <type>record</>
373         data type, then an alias or the key word <literal>AS</> must
374         be present, followed by a column definition list in the form
375         <literal>( <replaceable
376         class="parameter">column_name</replaceable> <replaceable
377         class="parameter">data_type</replaceable> <optional>, ... </>
378         )</literal>.  The column definition list must match the actual
379         number and types of columns returned by the function.
380        </para>
381       </listitem>
382      </varlistentry>
383
384      <varlistentry>
385       <term><replaceable class="parameter">join_type</replaceable></term>
386       <listitem>
387        <para>
388         One of
389         <itemizedlist>
390          <listitem>
391           <para><literal>[ INNER ] JOIN</literal></para>
392          </listitem>
393          <listitem>
394           <para><literal>LEFT [ OUTER ] JOIN</literal></para>
395          </listitem>
396          <listitem>
397           <para><literal>RIGHT [ OUTER ] JOIN</literal></para>
398          </listitem>
399          <listitem>
400           <para><literal>FULL [ OUTER ] JOIN</literal></para>
401          </listitem>
402          <listitem>
403           <para><literal>CROSS JOIN</literal></para>
404          </listitem>
405         </itemizedlist>
406
407         For the <literal>INNER</> and <literal>OUTER</> join types, a
408         join condition must be specified, namely exactly one of
409         <literal>NATURAL</>, <literal>ON <replaceable
410         class="parameter">join_condition</replaceable></literal>, or
411         <literal>USING (<replaceable
412         class="parameter">join_column</replaceable> [, ...])</literal>.
413         See below for the meaning.  For <literal>CROSS JOIN</literal>,
414         none of these clauses can appear.
415        </para>
416
417        <para>
418         A <literal>JOIN</literal> clause combines two
419         <literal>FROM</> items.  Use parentheses if necessary to
420         determine the order of nesting.  In the absence of parentheses,
421         <literal>JOIN</literal>s nest left-to-right.  In any case
422         <literal>JOIN</literal> binds more tightly than the commas
423         separating <literal>FROM</> items.
424        </para>
425
426        <para>
427         <literal>CROSS JOIN</> and <literal>INNER JOIN</literal>
428         produce a simple Cartesian product, the same result as you get from
429         listing the two items at the top level of <literal>FROM</>,
430         but restricted by the join condition (if any).
431         <literal>CROSS JOIN</> is equivalent to <literal>INNER JOIN ON
432         (TRUE)</>, that is, no rows are removed by qualification.
433         These join types are just a notational convenience, since they
434         do nothing you couldn't do with plain <literal>FROM</> and
435         <literal>WHERE</>.
436        </para>
437
438        <para>
439         <literal>LEFT OUTER JOIN</> returns all rows in the qualified
440         Cartesian product (i.e., all combined rows that pass its join
441         condition), plus one copy of each row in the left-hand table
442         for which there was no right-hand row that passed the join
443         condition.  This left-hand row is extended to the full width
444         of the joined table by inserting null values for the
445         right-hand columns.  Note that only the <literal>JOIN</>
446         clause's own condition is considered while deciding which rows
447         have matches.  Outer conditions are applied afterwards.
448        </para>
449
450        <para>
451         Conversely, <literal>RIGHT OUTER JOIN</> returns all the
452         joined rows, plus one row for each unmatched right-hand row
453         (extended with nulls on the left).  This is just a notational
454         convenience, since you could convert it to a <literal>LEFT
455         OUTER JOIN</> by switching the left and right inputs.
456        </para>
457
458        <para>
459         <literal>FULL OUTER JOIN</> returns all the joined rows, plus
460         one row for each unmatched left-hand row (extended with nulls
461         on the right), plus one row for each unmatched right-hand row
462         (extended with nulls on the left).
463        </para>
464       </listitem>
465      </varlistentry>
466
467      <varlistentry>
468       <term><literal>ON <replaceable class="parameter">join_condition</replaceable></literal></term>
469       <listitem>
470        <para>
471         <replaceable class="parameter">join_condition</replaceable> is
472         an expression resulting in a value of type
473         <type>boolean</type> (similar to a <literal>WHERE</literal>
474         clause) that specifies which rows in a join are considered to
475         match.
476        </para>
477       </listitem>
478      </varlistentry>
479
480      <varlistentry>
481       <term><literal>USING ( <replaceable class="parameter">join_column</replaceable> [, ...] )</literal></term>
482       <listitem>
483        <para>
484         A clause of the form <literal>USING ( a, b, ... )</literal> is
485         shorthand for <literal>ON left_table.a = right_table.a AND
486         left_table.b = right_table.b ...</literal>.  Also,
487         <literal>USING</> implies that only one of each pair of
488         equivalent columns will be included in the join output, not
489         both.
490        </para>
491       </listitem>
492      </varlistentry>
493
494      <varlistentry>
495       <term><literal>NATURAL</literal></term>
496       <listitem>
497        <para>
498         <literal>NATURAL</literal> is shorthand for a
499         <literal>USING</> list that mentions all columns in the two
500         tables that have the same names.
501        </para>
502       </listitem>
503      </varlistentry>
504     </variablelist>
505    </para>
506   </refsect2>
507
508   <refsect2 id="SQL-WHERE">
509    <title id="sql-where-title"><literal>WHERE</literal> Clause</title>
510
511    <para>
512     The optional <literal>WHERE</literal> clause has the general form
513 <synopsis>
514 WHERE <replaceable class="parameter">condition</replaceable>
515 </synopsis>
516     where <replaceable class="parameter">condition</replaceable> is
517     any expression that evaluates to a result of type
518     <type>boolean</type>.  Any row that does not satisfy this
519     condition will be eliminated from the output.  A row satisfies the
520     condition if it returns true when the actual row values are
521     substituted for any variable references.
522    </para>
523   </refsect2>
524
525   <refsect2 id="SQL-GROUPBY">
526    <title id="sql-groupby-title"><literal>GROUP BY</literal> Clause</title>
527
528    <para>
529     The optional <literal>GROUP BY</literal> clause has the general form
530 <synopsis>
531 GROUP BY <replaceable class="parameter">expression</replaceable> [, ...]
532 </synopsis>
533    </para>
534
535    <para>
536     <literal>GROUP BY</literal> will condense into a single row all
537     selected rows that share the same values for the grouped
538     expressions.  <replaceable
539     class="parameter">expression</replaceable> can be an input column
540     name, or the name or ordinal number of an output column
541     (<command>SELECT</command> list item), or an arbitrary
542     expression formed from input-column values.  In case of ambiguity,
543     a <literal>GROUP BY</literal> name will be interpreted as an
544     input-column name rather than an output column name.
545    </para>
546
547    <para>
548     Aggregate functions, if any are used, are computed across all rows
549     making up each group, producing a separate value for each group
550     (whereas without <literal>GROUP BY</literal>, an aggregate
551     produces a single value computed across all the selected rows).
552     When <literal>GROUP BY</literal> is present, it is not valid for
553     the <command>SELECT</command> list expressions to refer to
554     ungrouped columns except within aggregate functions or if the
555     ungrouped column is functionally dependent on the grouped columns,
556     since there would otherwise be more than one possible value to
557     return for an ungrouped column.  A functional dependency exists if
558     the grouped columns (or a subset thereof) are the primary key of
559     the table containing the ungrouped column.
560    </para>
561   </refsect2>
562
563   <refsect2 id="SQL-HAVING">
564    <title id="sql-having-title"><literal>HAVING</literal> Clause</title>
565
566    <para>
567     The optional <literal>HAVING</literal> clause has the general form
568 <synopsis>
569 HAVING <replaceable class="parameter">condition</replaceable>
570 </synopsis>
571     where <replaceable class="parameter">condition</replaceable> is
572     the same as specified for the <literal>WHERE</literal> clause.
573    </para>
574
575    <para>
576     <literal>HAVING</literal> eliminates group rows that do not
577     satisfy the condition.  <literal>HAVING</literal> is different
578     from <literal>WHERE</literal>: <literal>WHERE</literal> filters
579     individual rows before the application of <literal>GROUP
580     BY</literal>, while <literal>HAVING</literal> filters group rows
581     created by <literal>GROUP BY</literal>.  Each column referenced in
582     <replaceable class="parameter">condition</replaceable> must
583     unambiguously reference a grouping column, unless the reference
584     appears within an aggregate function.
585    </para>
586
587    <para>
588     The presence of <literal>HAVING</literal> turns a query into a grouped
589     query even if there is no <literal>GROUP BY</> clause.  This is the
590     same as what happens when the query contains aggregate functions but
591     no <literal>GROUP BY</> clause.  All the selected rows are considered to
592     form a single group, and the <command>SELECT</command> list and
593     <literal>HAVING</literal> clause can only reference table columns from
594     within aggregate functions.  Such a query will emit a single row if the
595     <literal>HAVING</literal> condition is true, zero rows if it is not true.
596    </para>
597   </refsect2>
598
599   <refsect2 id="SQL-WINDOW">
600    <title id="sql-window-title"><literal>WINDOW</literal> Clause</title>
601
602    <para>
603     The optional <literal>WINDOW</literal> clause has the general form
604 <synopsis>
605 WINDOW <replaceable class="parameter">window_name</replaceable> AS ( <replaceable class="parameter">window_definition</replaceable> ) [, ...]
606 </synopsis>
607     where <replaceable class="parameter">window_name</replaceable> is
608     a name that can be referenced from subsequent window definitions or
609     <literal>OVER</> clauses, and
610     <replaceable class="parameter">window_definition</replaceable> is
611 <synopsis>
612 [ <replaceable class="parameter">existing_window_name</replaceable> ]
613 [ PARTITION BY <replaceable class="parameter">expression</replaceable> [, ...] ]
614 [ ORDER BY <replaceable class="parameter">expression</replaceable> [ ASC | DESC | USING <replaceable class="parameter">operator</replaceable> ] [ NULLS { FIRST | LAST } ] [, ...] ]
615 [ <replaceable class="parameter">frame_clause</replaceable> ]
616 </synopsis>
617    </para>
618
619    <para>
620     If an <replaceable class="parameter">existing_window_name</replaceable>
621     is specified it must refer to an earlier entry in the <literal>WINDOW</>
622     list; the new window copies its partitioning clause from that entry,
623     as well as its ordering clause if any.  In this case the new window cannot
624     specify its own <literal>PARTITION BY</> clause, and it can specify
625     <literal>ORDER BY</> only if the copied window does not have one.
626     The new window always uses its own frame clause; the copied window
627     must not specify a frame clause.
628    </para>
629
630    <para>
631     The elements of the <literal>PARTITION BY</> list are interpreted in
632     much the same fashion as elements of a
633     <xref linkend="sql-groupby" endterm="sql-groupby-title">, except that
634     they are always simple expressions and never the name or number of an
635     output column.
636     Another difference is that these expressions can contain aggregate
637     function calls, which are not allowed in a regular <literal>GROUP BY</>
638     clause.  They are allowed here because windowing occurs after grouping
639     and aggregation.
640    </para>
641
642    <para>
643     Similarly, the elements of the <literal>ORDER BY</> list are interpreted
644     in much the same fashion as elements of an
645     <xref linkend="sql-orderby" endterm="sql-orderby-title">, except that
646     the expressions are always taken as simple expressions and never the name
647     or number of an output column.
648    </para>
649
650    <para>
651     The optional <replaceable class="parameter">frame_clause</> defines
652     the <firstterm>window frame</> for window functions that depend on the
653     frame (not all do).  The window frame is a set of related rows for
654     each row of the query (called the <firstterm>current row</>).
655     The <replaceable class="parameter">frame_clause</> can be one of
656
657 <synopsis>
658 [ RANGE | ROWS ] <replaceable>frame_start</>
659 [ RANGE | ROWS ] BETWEEN <replaceable>frame_start</> AND <replaceable>frame_end</>
660 </synopsis>
661
662     where <replaceable>frame_start</> and <replaceable>frame_end</> can be
663     one of
664
665 <synopsis>
666 UNBOUNDED PRECEDING
667 <replaceable>value</replaceable> PRECEDING
668 CURRENT ROW
669 <replaceable>value</replaceable> FOLLOWING
670 UNBOUNDED FOLLOWING
671 </synopsis>
672
673     If <replaceable>frame_end</> is omitted it defaults to <literal>CURRENT
674     ROW</>.  Restrictions are that
675     <replaceable>frame_start</> cannot be <literal>UNBOUNDED FOLLOWING</>,
676     <replaceable>frame_end</> cannot be <literal>UNBOUNDED PRECEDING</>,
677     and the <replaceable>frame_end</> choice cannot appear earlier in the
678     above list than the <replaceable>frame_start</> choice &mdash; for example
679     <literal>RANGE BETWEEN CURRENT ROW AND <replaceable>value</>
680     PRECEDING</literal> is not allowed.
681    </para>
682
683    <para>
684     The default framing option is <literal>RANGE UNBOUNDED PRECEDING</>,
685     which is the same as <literal>RANGE BETWEEN UNBOUNDED PRECEDING AND
686     CURRENT ROW</>; it sets the frame to be all rows from the partition start
687     up through the current row's last peer in the <literal>ORDER BY</>
688     ordering (which means all rows if there is no <literal>ORDER BY</>).
689     In general, <literal>UNBOUNDED PRECEDING</> means that the frame
690     starts with the first row of the partition, and similarly
691     <literal>UNBOUNDED FOLLOWING</> means that the frame ends with the last
692     row of the partition (regardless of <literal>RANGE</> or <literal>ROWS</>
693     mode).  In <literal>ROWS</> mode, <literal>CURRENT ROW</>
694     means that the frame starts or ends with the current row; but in
695     <literal>RANGE</> mode it means that the frame starts or ends with
696     the current row's first or last peer in the <literal>ORDER BY</> ordering.
697     The <replaceable>value</> <literal>PRECEDING</> and
698     <replaceable>value</> <literal>FOLLOWING</> cases are currently only
699     allowed in <literal>ROWS</> mode.  They indicate that the frame starts
700     or ends with the row that many rows before or after the current row.
701     <replaceable>value</replaceable> must be an integer expression not
702     containing any variables, aggregate functions, or window functions.
703     The value must not be null or negative; but it can be zero, which
704     selects the current row itself.
705    </para>
706
707    <para>
708     Beware that the <literal>ROWS</> options can produce unpredictable
709     results if the <literal>ORDER BY</> ordering does not order the rows
710     uniquely.  The <literal>RANGE</> options are designed to ensure that
711     rows that are peers in the <literal>ORDER BY</> ordering are treated
712     alike; any two peer rows will be both in or both not in the frame.
713    </para>
714
715    <para>
716     The purpose of a <literal>WINDOW</literal> clause is to specify the
717     behavior of <firstterm>window functions</> appearing in the query's
718     <xref linkend="sql-select-list" endterm="sql-select-list-title"> or
719     <xref linkend="sql-orderby" endterm="sql-orderby-title">.  These functions
720     can reference the <literal>WINDOW</literal> clause entries by name
721     in their <literal>OVER</> clauses.  A <literal>WINDOW</literal> clause
722     entry does not have to be referenced anywhere, however; if it is not
723     used in the query it is simply ignored.  It is possible to use window
724     functions without any <literal>WINDOW</literal> clause at all, since
725     a window function call can specify its window definition directly in
726     its <literal>OVER</> clause.  However, the <literal>WINDOW</literal>
727     clause saves typing when the same window definition is needed for more
728     than one window function.
729    </para>
730
731    <para>
732     Window functions are described in detail in
733     <xref linkend="tutorial-window">,
734     <xref linkend="syntax-window-functions">, and
735     <xref linkend="queries-window">.
736    </para>
737   </refsect2>
738
739   <refsect2 id="sql-select-list">
740    <title id="sql-select-list-title"><command>SELECT</command> List</title>
741
742    <para>
743     The <command>SELECT</command> list (between the key words
744     <literal>SELECT</> and <literal>FROM</>) specifies expressions
745     that form the output rows of the <command>SELECT</command>
746     statement.  The expressions can (and usually do) refer to columns
747     computed in the <literal>FROM</> clause.
748    </para>
749
750    <para>
751     Just as in a table, every output column of a <command>SELECT</command>
752     has a name.  In a simple <command>SELECT</command> this name is just
753     used to label the column for display, but when the <command>SELECT</>
754     is a sub-query of a larger query, the name is seen by the larger query
755     as the column name of the virtual table produced by the sub-query.
756     To specify the name to use for an output column, write
757     <literal>AS</> <replaceable class="parameter">output_name</replaceable>
758     after the column's expression.  (You can omit <literal>AS</literal>,
759     but only if the desired output name does not match any
760     <productname>PostgreSQL</productname> keyword (see <xref
761     linkend="sql-keywords-appendix">).  For protection against possible
762     future keyword additions, it is recommended that you always either
763     write <literal>AS</literal> or double-quote the output name.)
764     If you do not specify a column name, a name is chosen automatically
765     by <productname>PostgreSQL</productname>.  If the column's expression
766     is a simple column reference then the chosen name is the same as that
767     column's name; in more complex cases a generated name looking like
768     <literal>?column<replaceable>N</>?</literal> is usually chosen.
769    </para>
770
771    <para>
772     An output column's name can be used to refer to the column's value in
773     <literal>ORDER BY</> and <literal>GROUP BY</> clauses, but not in the
774     <literal>WHERE</> or <literal>HAVING</> clauses; there you must write
775     out the expression instead.
776    </para>
777
778    <para>
779     Instead of an expression, <literal>*</literal> can be written in
780     the output list as a shorthand for all the columns of the selected
781     rows.  Also, you can write <literal><replaceable
782     class="parameter">table_name</replaceable>.*</literal> as a
783     shorthand for the columns coming from just that table.  In these
784     cases it is not possible to specify new names with <literal>AS</>;
785     the output column names will be the same as the table columns' names.
786    </para>
787   </refsect2>
788
789   <refsect2 id="sql-distinct">
790    <title id="sql-distinct-title"><literal>DISTINCT</literal> Clause</title>
791
792    <para>
793     If <literal>SELECT DISTINCT</> is specified, all duplicate rows are
794     removed from the result set (one row is kept from each group of
795     duplicates).  <literal>SELECT ALL</> specifies the opposite: all rows are
796     kept; that is the default.
797    </para>
798
799    <para>
800     <literal>SELECT DISTINCT ON ( <replaceable
801     class="parameter">expression</replaceable> [, ...] )</literal>
802     keeps only the first row of each set of rows where the given
803     expressions evaluate to equal.  The <literal>DISTINCT ON</literal>
804     expressions are interpreted using the same rules as for
805     <literal>ORDER BY</> (see above).  Note that the <quote>first
806     row</quote> of each set is unpredictable unless <literal>ORDER
807     BY</> is used to ensure that the desired row appears first.  For
808     example:
809 <programlisting>
810 SELECT DISTINCT ON (location) location, time, report
811     FROM weather_reports
812     ORDER BY location, time DESC;
813 </programlisting>
814     retrieves the most recent weather report for each location.  But
815     if we had not used <literal>ORDER BY</> to force descending order
816     of time values for each location, we'd have gotten a report from
817     an unpredictable time for each location.
818    </para>
819
820    <para>
821     The <literal>DISTINCT ON</> expression(s) must match the leftmost
822     <literal>ORDER BY</> expression(s).  The <literal>ORDER BY</> clause
823     will normally contain additional expression(s) that determine the
824     desired precedence of rows within each <literal>DISTINCT ON</> group.
825    </para>
826   </refsect2>
827
828   <refsect2 id="SQL-UNION">
829    <title id="sql-union-title"><literal>UNION</literal> Clause</title>
830
831    <para>
832     The <literal>UNION</literal> clause has this general form:
833 <synopsis>
834 <replaceable class="parameter">select_statement</replaceable> UNION [ ALL | DISTINCT ] <replaceable class="parameter">select_statement</replaceable>
835 </synopsis>
836     <replaceable class="parameter">select_statement</replaceable> is
837     any <command>SELECT</command> statement without an <literal>ORDER
838     BY</>, <literal>LIMIT</>, <literal>FOR UPDATE</literal>, or
839     <literal>FOR SHARE</literal> clause.
840     (<literal>ORDER BY</> and <literal>LIMIT</> can be attached to a
841     subexpression if it is enclosed in parentheses.  Without
842     parentheses, these clauses will be taken to apply to the result of
843     the <literal>UNION</literal>, not to its right-hand input
844     expression.)
845    </para>
846
847    <para>
848     The <literal>UNION</literal> operator computes the set union of
849     the rows returned by the involved <command>SELECT</command>
850     statements.  A row is in the set union of two result sets if it
851     appears in at least one of the result sets.  The two
852     <command>SELECT</command> statements that represent the direct
853     operands of the <literal>UNION</literal> must produce the same
854     number of columns, and corresponding columns must be of compatible
855     data types.
856    </para>
857
858    <para>
859     The result of <literal>UNION</> does not contain any duplicate
860     rows unless the <literal>ALL</> option is specified.
861     <literal>ALL</> prevents elimination of duplicates.  (Therefore,
862     <literal>UNION ALL</> is usually significantly quicker than
863     <literal>UNION</>; use <literal>ALL</> when you can.)
864     <literal>DISTINCT</> can be written to explicitly specify the
865     default behavior of eliminating duplicate rows.
866    </para>
867
868    <para>
869     Multiple <literal>UNION</> operators in the same
870     <command>SELECT</command> statement are evaluated left to right,
871     unless otherwise indicated by parentheses.
872    </para>
873
874    <para>
875     Currently, <literal>FOR UPDATE</> and <literal>FOR SHARE</> cannot be
876     specified either for a <literal>UNION</> result or for any input of a
877     <literal>UNION</>.
878    </para>
879   </refsect2>
880
881   <refsect2 id="SQL-INTERSECT">
882    <title id="sql-intersect-title"><literal>INTERSECT</literal> Clause</title>
883
884    <para>
885     The <literal>INTERSECT</literal> clause has this general form:
886 <synopsis>
887 <replaceable class="parameter">select_statement</replaceable> INTERSECT [ ALL | DISTINCT ] <replaceable class="parameter">select_statement</replaceable>
888 </synopsis>
889     <replaceable class="parameter">select_statement</replaceable> is
890     any <command>SELECT</command> statement without an <literal>ORDER
891     BY</>, <literal>LIMIT</>, <literal>FOR UPDATE</literal>, or
892     <literal>FOR SHARE</literal> clause.
893    </para>
894
895    <para>
896     The <literal>INTERSECT</literal> operator computes the set
897     intersection of the rows returned by the involved
898     <command>SELECT</command> statements.  A row is in the
899     intersection of two result sets if it appears in both result sets.
900    </para>
901
902    <para>
903     The result of <literal>INTERSECT</literal> does not contain any
904     duplicate rows unless the <literal>ALL</> option is specified.
905     With <literal>ALL</>, a row that has <replaceable>m</> duplicates in the
906     left table and <replaceable>n</> duplicates in the right table will appear
907     min(<replaceable>m</>,<replaceable>n</>) times in the result set.
908     <literal>DISTINCT</> can be written to explicitly specify the
909     default behavior of eliminating duplicate rows.
910    </para>
911
912    <para>
913     Multiple <literal>INTERSECT</literal> operators in the same
914     <command>SELECT</command> statement are evaluated left to right,
915     unless parentheses dictate otherwise.
916     <literal>INTERSECT</literal> binds more tightly than
917     <literal>UNION</literal>.  That is, <literal>A UNION B INTERSECT
918     C</literal> will be read as <literal>A UNION (B INTERSECT
919     C)</literal>.
920    </para>
921
922    <para>
923     Currently, <literal>FOR UPDATE</> and <literal>FOR SHARE</> cannot be
924     specified either for an <literal>INTERSECT</> result or for any input of
925     an <literal>INTERSECT</>.
926    </para>
927   </refsect2>
928
929   <refsect2 id="SQL-EXCEPT">
930    <title id="sql-except-title"><literal>EXCEPT</literal> Clause</title>
931
932    <para>
933     The <literal>EXCEPT</literal> clause has this general form:
934 <synopsis>
935 <replaceable class="parameter">select_statement</replaceable> EXCEPT [ ALL | DISTINCT ] <replaceable class="parameter">select_statement</replaceable>
936 </synopsis>
937     <replaceable class="parameter">select_statement</replaceable> is
938     any <command>SELECT</command> statement without an <literal>ORDER
939     BY</>, <literal>LIMIT</>, <literal>FOR UPDATE</literal>, or
940     <literal>FOR SHARE</literal> clause.
941    </para>
942
943    <para>
944     The <literal>EXCEPT</literal> operator computes the set of rows
945     that are in the result of the left <command>SELECT</command>
946     statement but not in the result of the right one.
947    </para>
948
949    <para>
950     The result of <literal>EXCEPT</literal> does not contain any
951     duplicate rows unless the <literal>ALL</> option is specified.
952     With <literal>ALL</>, a row that has <replaceable>m</> duplicates in the
953     left table and <replaceable>n</> duplicates in the right table will appear
954     max(<replaceable>m</>-<replaceable>n</>,0) times in the result set.
955     <literal>DISTINCT</> can be written to explicitly specify the
956     default behavior of eliminating duplicate rows.
957    </para>
958
959    <para>
960     Multiple <literal>EXCEPT</literal> operators in the same
961     <command>SELECT</command> statement are evaluated left to right,
962     unless parentheses dictate otherwise.  <literal>EXCEPT</> binds at
963     the same level as <literal>UNION</>.
964    </para>
965
966    <para>
967     Currently, <literal>FOR UPDATE</> and <literal>FOR SHARE</> cannot be
968     specified either for an <literal>EXCEPT</> result or for any input of
969     an <literal>EXCEPT</>.
970    </para>
971   </refsect2>
972
973   <refsect2 id="SQL-ORDERBY">
974    <title id="sql-orderby-title"><literal>ORDER BY</literal> Clause</title>
975
976    <para>
977     The optional <literal>ORDER BY</literal> clause has this general form:
978 <synopsis>
979 ORDER BY <replaceable class="parameter">expression</replaceable> [ ASC | DESC | USING <replaceable class="parameter">operator</replaceable> ] [ NULLS { FIRST | LAST } ] [, ...]
980 </synopsis>
981     The <literal>ORDER BY</literal> clause causes the result rows to
982     be sorted according to the specified expression(s).  If two rows are
983     equal according to the leftmost expression, they are compared
984     according to the next expression and so on.  If they are equal
985     according to all specified expressions, they are returned in
986     an implementation-dependent order.
987    </para>
988
989    <para>
990     Each <replaceable class="parameter">expression</replaceable> can be the
991     name or ordinal number of an output column
992     (<command>SELECT</command> list item), or it can be an arbitrary
993     expression formed from input-column values.
994    </para>
995
996    <para>
997     The ordinal number refers to the ordinal (left-to-right) position
998     of the output column. This feature makes it possible to define an
999     ordering on the basis of a column that does not have a unique
1000     name.  This is never absolutely necessary because it is always
1001     possible to assign a name to an output column using the
1002     <literal>AS</> clause.
1003    </para>
1004
1005    <para>
1006     It is also possible to use arbitrary expressions in the
1007     <literal>ORDER BY</literal> clause, including columns that do not
1008     appear in the <command>SELECT</command> output list.  Thus the
1009     following statement is valid:
1010 <programlisting>
1011 SELECT name FROM distributors ORDER BY code;
1012 </programlisting>
1013     A limitation of this feature is that an <literal>ORDER BY</>
1014     clause applying to the result of a <literal>UNION</>,
1015     <literal>INTERSECT</>, or <literal>EXCEPT</> clause can only
1016     specify an output column name or number, not an expression.
1017    </para>
1018
1019    <para>
1020     If an <literal>ORDER BY</> expression is a simple name that
1021     matches both an output column name and an input column name,
1022     <literal>ORDER BY</> will interpret it as the output column name.
1023     This is the opposite of the choice that <literal>GROUP BY</> will
1024     make in the same situation.  This inconsistency is made to be
1025     compatible with the SQL standard.
1026    </para>
1027
1028    <para>
1029     Optionally one can add the key word <literal>ASC</> (ascending) or
1030     <literal>DESC</> (descending) after any expression in the
1031     <literal>ORDER BY</> clause.  If not specified, <literal>ASC</> is
1032     assumed by default.  Alternatively, a specific ordering operator
1033     name can be specified in the <literal>USING</> clause.
1034     An ordering operator must be a less-than or greater-than
1035     member of some B-tree operator family.
1036     <literal>ASC</> is usually equivalent to <literal>USING &lt;</> and
1037     <literal>DESC</> is usually equivalent to <literal>USING &gt;</>.
1038     (But the creator of a user-defined data type can define exactly what the
1039     default sort ordering is, and it might correspond to operators with other
1040     names.)
1041    </para>
1042
1043    <para>
1044     If <literal>NULLS LAST</> is specified, null values sort after all
1045     non-null values; if <literal>NULLS FIRST</> is specified, null values
1046     sort before all non-null values.  If neither is specified, the default
1047     behavior is <literal>NULLS LAST</> when <literal>ASC</> is specified
1048     or implied, and <literal>NULLS FIRST</> when <literal>DESC</> is specified
1049     (thus, the default is to act as though nulls are larger than non-nulls).
1050     When <literal>USING</> is specified, the default nulls ordering depends
1051     on whether the operator is a less-than or greater-than operator.
1052    </para>
1053
1054    <para>
1055     Note that ordering options apply only to the expression they follow;
1056     for example <literal>ORDER BY x, y DESC</> does not mean
1057     the same thing as <literal>ORDER BY x DESC, y DESC</>.
1058    </para>
1059
1060    <para>
1061     Character-string data is sorted according to the locale-specific
1062     collation order that was established when the database was created.
1063    </para>
1064   </refsect2>
1065
1066   <refsect2 id="SQL-LIMIT">
1067    <title id="sql-limit-title"><literal>LIMIT</literal> Clause</title>
1068
1069    <para>
1070     The <literal>LIMIT</literal> clause consists of two independent
1071     sub-clauses:
1072 <synopsis>
1073 LIMIT { <replaceable class="parameter">count</replaceable> | ALL }
1074 OFFSET <replaceable class="parameter">start</replaceable>
1075 </synopsis>
1076     <replaceable class="parameter">count</replaceable> specifies the
1077     maximum number of rows to return, while <replaceable
1078     class="parameter">start</replaceable> specifies the number of rows
1079     to skip before starting to return rows.  When both are specified,
1080     <replaceable class="parameter">start</replaceable> rows are skipped
1081     before starting to count the <replaceable
1082     class="parameter">count</replaceable> rows to be returned.
1083    </para>
1084
1085    <para>
1086     If the <replaceable class="parameter">count</replaceable> expression
1087     evaluates to NULL, it is treated as <literal>LIMIT ALL</>, i.e., no
1088     limit.  If <replaceable class="parameter">start</replaceable> evaluates
1089     to NULL, it is treated the same as <literal>OFFSET 0</>.
1090    </para>
1091
1092    <para>
1093     SQL:2008 introduced a different syntax to achieve the same thing,
1094     which <productname>PostgreSQL</> also supports.  It is:
1095 <synopsis>
1096 OFFSET <replaceable class="parameter">start</replaceable> { ROW | ROWS }
1097 FETCH { FIRST | NEXT } [ <replaceable class="parameter">count</replaceable> ] { ROW | ROWS } ONLY
1098 </synopsis>
1099     According to the standard, the <literal>OFFSET</literal> clause must come
1100     before the <literal>FETCH</literal> clause if both are present; but
1101     <productname>PostgreSQL</> is laxer and allows either order.
1102     <literal>ROW</literal>
1103     and <literal>ROWS</literal> as well as <literal>FIRST</literal>
1104     and <literal>NEXT</literal> are noise words that don't influence
1105     the effects of these clauses.  In this syntax, when using expressions
1106     other than simple constants for <replaceable class="parameter">start</>
1107     or <replaceable class="parameter">count</replaceable>, parentheses will be
1108     necessary in most cases.  If <replaceable class="parameter">count</> is
1109     omitted in <literal>FETCH</>, it defaults to 1.
1110    </para>
1111
1112    <para>
1113     When using <literal>LIMIT</>, it is a good idea to use an
1114     <literal>ORDER BY</> clause that constrains the result rows into a
1115     unique order.  Otherwise you will get an unpredictable subset of
1116     the query's rows &mdash; you might be asking for the tenth through
1117     twentieth rows, but tenth through twentieth in what ordering?  You
1118     don't know what ordering unless you specify <literal>ORDER BY</>.
1119    </para>
1120
1121    <para>
1122     The query planner takes <literal>LIMIT</> into account when
1123     generating a query plan, so you are very likely to get different
1124     plans (yielding different row orders) depending on what you use
1125     for <literal>LIMIT</> and <literal>OFFSET</>.  Thus, using
1126     different <literal>LIMIT</>/<literal>OFFSET</> values to select
1127     different subsets of a query result <emphasis>will give
1128     inconsistent results</emphasis> unless you enforce a predictable
1129     result ordering with <literal>ORDER BY</>.  This is not a bug; it
1130     is an inherent consequence of the fact that SQL does not promise
1131     to deliver the results of a query in any particular order unless
1132     <literal>ORDER BY</> is used to constrain the order.
1133    </para>
1134
1135    <para>
1136     It is even possible for repeated executions of the same <literal>LIMIT</>
1137     query to return different subsets of the rows of a table, if there
1138     is not an <literal>ORDER BY</> to enforce selection of a deterministic
1139     subset.  Again, this is not a bug; determinism of the results is
1140     simply not guaranteed in such a case.
1141    </para>
1142   </refsect2>
1143
1144   <refsect2 id="SQL-FOR-UPDATE-SHARE">
1145    <title id="sql-for-update-share-title"><literal>FOR UPDATE</literal>/<literal>FOR SHARE</literal> Clause</title>
1146
1147    <para>
1148     The <literal>FOR UPDATE</literal> clause has this form:
1149 <synopsis>
1150 FOR UPDATE [ OF <replaceable class="parameter">table_name</replaceable> [, ...] ] [ NOWAIT ]
1151 </synopsis>
1152    </para>
1153
1154    <para>
1155     The closely related <literal>FOR SHARE</literal> clause has this form:
1156 <synopsis>
1157 FOR SHARE [ OF <replaceable class="parameter">table_name</replaceable> [, ...] ] [ NOWAIT ]
1158 </synopsis>
1159    </para>
1160
1161    <para>
1162     <literal>FOR UPDATE</literal> causes the rows retrieved by the
1163     <command>SELECT</command> statement to be locked as though for
1164     update.  This prevents them from being modified or deleted by
1165     other transactions until the current transaction ends.  That is,
1166     other transactions that attempt <command>UPDATE</command>,
1167     <command>DELETE</command>, or <command>SELECT FOR UPDATE</command>
1168     of these rows will be blocked until the current transaction ends.
1169     Also, if an <command>UPDATE</command>, <command>DELETE</command>,
1170     or <command>SELECT FOR UPDATE</command> from another transaction
1171     has already locked a selected row or rows, <command>SELECT FOR
1172     UPDATE</command> will wait for the other transaction to complete,
1173     and will then lock and return the updated row (or no row, if the
1174     row was deleted).  Within a <literal>REPEATABLE READ</> or <literal>SERIALIZABLE</> transaction,
1175     however, an error will be thrown if a row to be locked has changed
1176     since the transaction started.  For further discussion see <xref
1177     linkend="mvcc">.
1178    </para>
1179
1180    <para>
1181     <literal>FOR SHARE</literal> behaves similarly, except that it
1182     acquires a shared rather than exclusive lock on each retrieved
1183     row.  A shared lock blocks other transactions from performing
1184     <command>UPDATE</command>, <command>DELETE</command>, or <command>SELECT
1185     FOR UPDATE</command> on these rows, but it does not prevent them
1186     from performing <command>SELECT FOR SHARE</command>.
1187    </para>
1188
1189    <para>
1190     To prevent the operation from waiting for other transactions to commit,
1191     use the <literal>NOWAIT</> option.  With <literal>NOWAIT</>, the statement
1192     reports an error, rather than waiting, if a selected row
1193     cannot be locked immediately.  Note that <literal>NOWAIT</> applies only
1194     to the row-level lock(s) &mdash; the required <literal>ROW SHARE</literal>
1195     table-level lock is still taken in the ordinary way (see
1196     <xref linkend="mvcc">).  You can use
1197     <xref linkend="sql-lock">
1198     with the <literal>NOWAIT</> option first,
1199     if you need to acquire the table-level lock without waiting.
1200    </para>
1201
1202    <para>
1203     If specific tables are named in <literal>FOR UPDATE</literal>
1204     or <literal>FOR SHARE</literal>,
1205     then only rows coming from those tables are locked; any other
1206     tables used in the <command>SELECT</command> are simply read as
1207     usual.  A <literal>FOR UPDATE</literal> or <literal>FOR SHARE</literal>
1208     clause without a table list affects all tables used in the statement.
1209     If <literal>FOR UPDATE</literal> or <literal>FOR SHARE</literal> is
1210     applied to a view or sub-query, it affects all tables used in
1211     the view or sub-query.
1212     However, <literal>FOR UPDATE</literal>/<literal>FOR SHARE</literal>
1213     do not apply to <literal>WITH</> queries referenced by the primary query.
1214     If you want row locking to occur within a <literal>WITH</> query, specify
1215     <literal>FOR UPDATE</literal> or <literal>FOR SHARE</literal> within the
1216     <literal>WITH</> query.
1217    </para>
1218
1219    <para>
1220     Multiple <literal>FOR UPDATE</literal> and <literal>FOR SHARE</literal>
1221     clauses can be written if it is necessary to specify different locking
1222     behavior for different tables.  If the same table is mentioned (or
1223     implicitly affected) by both <literal>FOR UPDATE</literal> and
1224     <literal>FOR SHARE</literal> clauses, then it is processed as
1225     <literal>FOR UPDATE</literal>.  Similarly, a table is processed
1226     as <literal>NOWAIT</> if that is specified in any of the clauses
1227     affecting it.
1228    </para>
1229
1230    <para>
1231     <literal>FOR UPDATE</literal> and <literal>FOR SHARE</literal> cannot be
1232     used in contexts where returned rows cannot be clearly identified with
1233     individual table rows; for example they cannot be used with aggregation.
1234    </para>
1235
1236    <para>
1237     When <literal>FOR UPDATE</literal> or <literal>FOR SHARE</literal>
1238     appears at the top level of a <command>SELECT</> query, the rows that
1239     are locked are exactly those that are returned by the query; in the
1240     case of a join query, the rows locked are those that contribute to
1241     returned join rows.  In addition, rows that satisfied the query
1242     conditions as of the query snapshot will be locked, although they
1243     will not be returned if they were updated after the snapshot
1244     and no longer satisfy the query conditions.  If a
1245     <literal>LIMIT</> is used, locking stops
1246     once enough rows have been returned to satisfy the limit (but note that
1247     rows skipped over by <literal>OFFSET</> will get locked).  Similarly,
1248     if <literal>FOR UPDATE</literal> or <literal>FOR SHARE</literal>
1249     is used in a cursor's query, only rows actually fetched or stepped past
1250     by the cursor will be locked.
1251    </para>
1252
1253    <para>
1254     When <literal>FOR UPDATE</literal> or <literal>FOR SHARE</literal>
1255     appears in a sub-<command>SELECT</>, the rows locked are those
1256     returned to the outer query by the sub-query.  This might involve
1257     fewer rows than inspection of the sub-query alone would suggest,
1258     since conditions from the outer query might be used to optimize
1259     execution of the sub-query.  For example,
1260 <programlisting>
1261 SELECT * FROM (SELECT * FROM mytable FOR UPDATE) ss WHERE col1 = 5;
1262 </programlisting>
1263     will lock only rows having <literal>col1 = 5</>, even though that
1264     condition is not textually within the sub-query.
1265    </para>
1266
1267   <caution>
1268    <para>
1269     Avoid locking a row and then modifying it within a later savepoint or
1270     <application>PL/pgSQL</application> exception block.  A subsequent
1271     rollback would cause the lock to be lost.  For example:
1272 <programlisting>
1273 BEGIN;
1274 SELECT * FROM mytable WHERE key = 1 FOR UPDATE;
1275 SAVEPOINT s;
1276 UPDATE mytable SET ... WHERE key = 1;
1277 ROLLBACK TO s;
1278 </programlisting>
1279     After the <command>ROLLBACK</>, the row is effectively unlocked, rather
1280     than returned to its pre-savepoint state of being locked but not modified.
1281     This hazard occurs if a row locked in the current transaction is updated
1282     or deleted, or if a shared lock is upgraded to exclusive: in all these
1283     cases, the former lock state is forgotten.  If the transaction is then
1284     rolled back to a state between the original locking command and the
1285     subsequent change, the row will appear not to be locked at all.  This is
1286     an implementation deficiency which will be addressed in a future release
1287     of <productname>PostgreSQL</productname>.
1288    </para>
1289   </caution>
1290
1291   <caution>
1292    <para>
1293     It is possible for a <command>SELECT</> command using <literal>ORDER
1294     BY</literal> and <literal>FOR UPDATE/SHARE</literal> to return rows out of
1295     order.  This is because <literal>ORDER BY</> is applied first.
1296     The command sorts the result, but might then block trying to obtain a lock
1297     on one or more of the rows.  Once the <literal>SELECT</> unblocks, some
1298     of the ordering column values might have been modified, leading to those
1299     rows appearing to be out of order (though they are in order in terms
1300     of the original column values).  This can be worked around at need by
1301     placing the <literal>FOR UPDATE/SHARE</literal> clause in a sub-query,
1302     for example
1303 <programlisting>
1304 SELECT * FROM (SELECT * FROM mytable FOR UPDATE) ss ORDER BY column1;
1305 </programlisting>
1306     Note that this will result in locking all rows of <structname>mytable</>,
1307     whereas <literal>FOR UPDATE</> at the top level would lock only the
1308     actually returned rows.  This can make for a significant performance
1309     difference, particularly if the <literal>ORDER BY</> is combined with
1310     <literal>LIMIT</> or other restrictions.  So this technique is recommended
1311     only if concurrent updates of the ordering columns are expected and a
1312     strictly sorted result is required.
1313    </para>
1314   </caution>
1315   </refsect2>
1316
1317   <refsect2 id="SQL-TABLE">
1318    <title><literal>TABLE</literal> Command</title>
1319
1320    <para>
1321     The command
1322 <programlisting>
1323 TABLE <replaceable class="parameter">name</replaceable>
1324 </programlisting>
1325     is completely equivalent to
1326 <programlisting>
1327 SELECT * FROM <replaceable class="parameter">name</replaceable>
1328 </programlisting>
1329     It can be used as a top-level command or as a space-saving syntax
1330     variant in parts of complex queries.
1331    </para>
1332   </refsect2>
1333  </refsect1>
1334
1335  <refsect1>
1336   <title>Examples</title>
1337
1338   <para>
1339    To join the table <literal>films</literal> with the table
1340    <literal>distributors</literal>:
1341
1342 <programlisting>
1343 SELECT f.title, f.did, d.name, f.date_prod, f.kind
1344     FROM distributors d, films f
1345     WHERE f.did = d.did
1346
1347        title       | did |     name     | date_prod  |   kind
1348 -------------------+-----+--------------+------------+----------
1349  The Third Man     | 101 | British Lion | 1949-12-23 | Drama
1350  The African Queen | 101 | British Lion | 1951-08-11 | Romantic
1351  ...
1352 </programlisting>
1353   </para>
1354
1355   <para>
1356    To sum the column <literal>len</literal> of all films and group
1357    the results by <literal>kind</literal>:
1358
1359 <programlisting>
1360 SELECT kind, sum(len) AS total FROM films GROUP BY kind;
1361
1362    kind   | total
1363 ----------+-------
1364  Action   | 07:34
1365  Comedy   | 02:58
1366  Drama    | 14:28
1367  Musical  | 06:42
1368  Romantic | 04:38
1369 </programlisting>
1370   </para>
1371
1372   <para>
1373    To sum the column <literal>len</literal> of all films, group
1374    the results by <literal>kind</literal> and show those group totals
1375    that are less than 5 hours:
1376
1377 <programlisting>
1378 SELECT kind, sum(len) AS total
1379     FROM films
1380     GROUP BY kind
1381     HAVING sum(len) &lt; interval '5 hours';
1382
1383    kind   | total
1384 ----------+-------
1385  Comedy   | 02:58
1386  Romantic | 04:38
1387 </programlisting>
1388   </para>
1389
1390   <para>
1391    The following two examples are identical ways of sorting the individual
1392    results according to the contents of the second column
1393    (<literal>name</literal>):
1394
1395 <programlisting>
1396 SELECT * FROM distributors ORDER BY name;
1397 SELECT * FROM distributors ORDER BY 2;
1398
1399  did |       name
1400 -----+------------------
1401  109 | 20th Century Fox
1402  110 | Bavaria Atelier
1403  101 | British Lion
1404  107 | Columbia
1405  102 | Jean Luc Godard
1406  113 | Luso films
1407  104 | Mosfilm
1408  103 | Paramount
1409  106 | Toho
1410  105 | United Artists
1411  111 | Walt Disney
1412  112 | Warner Bros.
1413  108 | Westward
1414 </programlisting>
1415   </para>
1416
1417   <para>
1418    The next example shows how to obtain the union of the tables
1419    <literal>distributors</literal> and
1420    <literal>actors</literal>, restricting the results to those that begin
1421    with the letter W in each table.  Only distinct rows are wanted, so the
1422    key word <literal>ALL</literal> is omitted.
1423
1424 <programlisting>
1425 distributors:               actors:
1426  did |     name              id |     name
1427 -----+--------------        ----+----------------
1428  108 | Westward               1 | Woody Allen
1429  111 | Walt Disney            2 | Warren Beatty
1430  112 | Warner Bros.           3 | Walter Matthau
1431  ...                         ...
1432
1433 SELECT distributors.name
1434     FROM distributors
1435     WHERE distributors.name LIKE 'W%'
1436 UNION
1437 SELECT actors.name
1438     FROM actors
1439     WHERE actors.name LIKE 'W%';
1440
1441       name
1442 ----------------
1443  Walt Disney
1444  Walter Matthau
1445  Warner Bros.
1446  Warren Beatty
1447  Westward
1448  Woody Allen
1449 </programlisting>
1450   </para>
1451
1452   <para>
1453    This example shows how to use a function in the <literal>FROM</>
1454    clause, both with and without a column definition list:
1455
1456 <programlisting>
1457 CREATE FUNCTION distributors(int) RETURNS SETOF distributors AS $$
1458     SELECT * FROM distributors WHERE did = $1;
1459 $$ LANGUAGE SQL;
1460
1461 SELECT * FROM distributors(111);
1462  did |    name
1463 -----+-------------
1464  111 | Walt Disney
1465
1466 CREATE FUNCTION distributors_2(int) RETURNS SETOF record AS $$
1467     SELECT * FROM distributors WHERE did = $1;
1468 $$ LANGUAGE SQL;
1469
1470 SELECT * FROM distributors_2(111) AS (f1 int, f2 text);
1471  f1  |     f2
1472 -----+-------------
1473  111 | Walt Disney
1474 </programlisting>
1475   </para>
1476
1477   <para>
1478    This example shows how to use a simple <literal>WITH</> clause:
1479
1480 <programlisting>
1481 WITH t AS (
1482     SELECT random() as x FROM generate_series(1, 3)
1483   )
1484 SELECT * FROM t
1485 UNION ALL
1486 SELECT * FROM t
1487
1488          x          
1489 --------------------
1490   0.534150459803641
1491   0.520092216785997
1492  0.0735620250925422
1493   0.534150459803641
1494   0.520092216785997
1495  0.0735620250925422
1496 </programlisting>
1497
1498    Notice that the <literal>WITH</> query was evaluated only once,
1499    so that we got two sets of the same three random values.
1500   </para>
1501
1502   <para>
1503    This example uses <literal>WITH RECURSIVE</literal> to find all
1504    subordinates (direct or indirect) of the employee Mary, and their
1505    level of indirectness, from a table that shows only direct
1506    subordinates:
1507
1508 <programlisting>
1509 WITH RECURSIVE employee_recursive(distance, employee_name, manager_name) AS (
1510     SELECT 1, employee_name, manager_name
1511     FROM employee
1512     WHERE manager_name = 'Mary'
1513   UNION ALL
1514     SELECT er.distance + 1, e.employee_name, e.manager_name
1515     FROM employee_recursive er, employee e
1516     WHERE er.employee_name = e.manager_name
1517   )
1518 SELECT distance, employee_name FROM employee_recursive;
1519 </programlisting>
1520
1521    Notice the typical form of recursive queries:
1522    an initial condition, followed by <literal>UNION</literal>,
1523    followed by the recursive part of the query. Be sure that the
1524    recursive part of the query will eventually return no tuples, or
1525    else the query will loop indefinitely.  (See <xref linkend="queries-with">
1526    for more examples.)
1527   </para>
1528  </refsect1>
1529
1530  <refsect1>
1531   <title>Compatibility</title>
1532
1533   <para>
1534    Of course, the <command>SELECT</command> statement is compatible
1535    with the SQL standard.  But there are some extensions and some
1536    missing features.
1537   </para>
1538
1539   <refsect2>
1540    <title>Omitted <literal>FROM</literal> Clauses</title>
1541
1542    <para>
1543     <productname>PostgreSQL</productname> allows one to omit the
1544     <literal>FROM</literal> clause.  It has a straightforward use to
1545     compute the results of simple expressions:
1546 <programlisting>
1547 SELECT 2+2;
1548
1549  ?column?
1550 ----------
1551         4
1552 </programlisting>
1553     Some other <acronym>SQL</acronym> databases cannot do this except
1554     by introducing a dummy one-row table from which to do the
1555     <command>SELECT</command>.
1556    </para>
1557
1558    <para>
1559     Note that if a <literal>FROM</literal> clause is not specified,
1560     the query cannot reference any database tables. For example, the
1561     following query is invalid:
1562 <programlisting>
1563 SELECT distributors.* WHERE distributors.name = 'Westward';
1564 </programlisting>
1565     <productname>PostgreSQL</productname> releases prior to
1566     8.1 would accept queries of this form, and add an implicit entry
1567     to the query's <literal>FROM</literal> clause for each table
1568     referenced by the query. This is no longer allowed.
1569    </para>
1570   </refsect2>
1571
1572   <refsect2>
1573    <title>Omitting the <literal>AS</literal> Key Word</title>
1574
1575    <para>
1576     In the SQL standard, the optional key word <literal>AS</> can be
1577     omitted before an output column name whenever the new column name
1578     is a valid column name (that is, not the same as any reserved
1579     keyword).  <productname>PostgreSQL</productname> is slightly more
1580     restrictive: <literal>AS</> is required if the new column name
1581     matches any keyword at all, reserved or not.  Recommended practice is
1582     to use <literal>AS</> or double-quote output column names, to prevent
1583     any possible conflict against future keyword additions.
1584    </para>
1585
1586    <para>
1587     In <literal>FROM</literal> items, both the standard and
1588     <productname>PostgreSQL</productname> allow <literal>AS</> to
1589     be omitted before an alias that is an unreserved keyword.  But
1590     this is impractical for output column names, because of syntactic
1591     ambiguities.
1592    </para>
1593   </refsect2>
1594
1595   <refsect2>
1596    <title><literal>ONLY</literal> and Parentheses</title>
1597
1598    <para>
1599     The SQL standard requires parentheses around the table name
1600     after <literal>ONLY</literal>, as in <literal>SELECT * FROM ONLY
1601     (tab1), ONLY (tab2) WHERE ...</literal>.  PostgreSQL supports that
1602     as well, but the parentheses are optional.  (This point applies
1603     equally to all SQL commands supporting the <literal>ONLY</literal>
1604     option.)
1605    </para>
1606   </refsect2>
1607
1608   <refsect2>
1609    <title>Namespace Available to <literal>GROUP BY</literal> and <literal>ORDER BY</literal></title>
1610
1611    <para>
1612     In the SQL-92 standard, an <literal>ORDER BY</literal> clause can
1613     only use output column names or numbers, while a <literal>GROUP
1614     BY</literal> clause can only use expressions based on input column
1615     names.  <productname>PostgreSQL</productname> extends each of
1616     these clauses to allow the other choice as well (but it uses the
1617     standard's interpretation if there is ambiguity).
1618     <productname>PostgreSQL</productname> also allows both clauses to
1619     specify arbitrary expressions.  Note that names appearing in an
1620     expression will always be taken as input-column names, not as
1621     output-column names.
1622    </para>
1623
1624    <para>
1625     SQL:1999 and later use a slightly different definition which is not
1626     entirely upward compatible with SQL-92.
1627     In most cases, however, <productname>PostgreSQL</productname>
1628     will interpret an <literal>ORDER BY</literal> or <literal>GROUP
1629     BY</literal> expression the same way SQL:1999 does.
1630    </para>
1631   </refsect2>
1632
1633   <refsect2>
1634    <title>Functional Dependencies</title>
1635
1636    <para>
1637     <productname>PostgreSQL</productname> recognizes functional dependency
1638     (allowing columns to be omitted from <literal>GROUP BY</>) only when
1639     a table's primary key is included in the <literal>GROUP BY</> list.
1640     The SQL standard specifies additional conditions that should be
1641     recognized.
1642    </para>
1643   </refsect2>
1644
1645   <refsect2>
1646    <title><literal>WINDOW</literal> Clause Restrictions</title>
1647
1648    <para>
1649     The SQL standard provides additional options for the window
1650     <replaceable class="parameter">frame_clause</>.
1651     <productname>PostgreSQL</productname> currently supports only the
1652     options listed above.
1653    </para>
1654   </refsect2>
1655
1656   <refsect2>
1657    <title><literal>LIMIT</literal> and <literal>OFFSET</literal></title>
1658
1659    <para>
1660     The clauses <literal>LIMIT</literal> and <literal>OFFSET</literal>
1661     are <productname>PostgreSQL</productname>-specific syntax, also
1662     used by <productname>MySQL</productname>.  The SQL:2008 standard
1663     has introduced the clauses <literal>OFFSET ... FETCH {FIRST|NEXT}
1664     ...</literal> for the same functionality, as shown above
1665     in <xref linkend="sql-limit" endterm="sql-limit-title">.  This
1666     syntax is also used by <productname>IBM DB2</productname>.
1667     (Applications written for <productname>Oracle</productname>
1668     frequently use a workaround involving the automatically
1669     generated <literal>rownum</literal> column, which is not available in
1670     PostgreSQL, to implement the effects of these clauses.)
1671    </para>
1672   </refsect2>
1673
1674   <refsect2>
1675    <title><literal>FOR UPDATE</> and <literal>FOR SHARE</></title>
1676
1677    <para>
1678     Although <literal>FOR UPDATE</> appears in the SQL standard, the
1679     standard allows it only as an option of <command>DECLARE CURSOR</>.
1680     <productname>PostgreSQL</productname> allows it in any <command>SELECT</>
1681     query as well as in sub-<command>SELECT</>s, but this is an extension.
1682     The <literal>FOR SHARE</> variant, and the <literal>NOWAIT</> option,
1683     do not appear in the standard.
1684    </para>
1685   </refsect2>
1686
1687   <refsect2>
1688    <title>Data-Modifying Statements in <literal>WITH</></title>
1689
1690    <para>
1691     <productname>PostgreSQL</productname> allows <command>INSERT</>,
1692     <command>UPDATE</>, and <command>DELETE</> to be used as <literal>WITH</>
1693     queries.  This is not found in the SQL standard.
1694    </para>
1695   </refsect2>
1696
1697   <refsect2>
1698    <title>Nonstandard Clauses</title>
1699
1700    <para>
1701     The clause <literal>DISTINCT ON</literal> is not defined in the
1702     SQL standard.
1703    </para>
1704   </refsect2>
1705  </refsect1>
1706 </refentry>