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