2 doc/src/sgml/ref/select.sgml
3 PostgreSQL documentation
6 <refentry id="SQL-SELECT">
8 <refentrytitle>SELECT</refentrytitle>
9 <manvolnum>7</manvolnum>
10 <refmiscinfo>SQL - Language Statements</refmiscinfo>
14 <refname>SELECT</refname>
15 <refname>TABLE</refname>
16 <refname>WITH</refname>
17 <refpurpose>retrieve rows from a table or view</refpurpose>
20 <indexterm zone="sql-select">
21 <primary>SELECT</primary>
24 <indexterm zone="sql-select">
25 <primary>TABLE command</primary>
28 <indexterm zone="sql-select">
29 <primary>WITH</primary>
30 <secondary>in SELECT</secondary>
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 ] [...] ]
50 <phrase>where <replaceable class="parameter">from_item</replaceable> can be one of:</phrase>
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> [, ...] ) ]
59 <phrase>and <replaceable class="parameter">with_query</replaceable> is:</phrase>
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> )
63 TABLE [ ONLY ] <replaceable class="parameter">table_name</replaceable> [ * ]
69 <title>Description</title>
72 <command>SELECT</command> retrieves rows from zero or more tables.
73 The general processing of <command>SELECT</command> is as follows:
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
83 (See <xref linkend="sql-with" endterm="sql-with-title"> below.)
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.)
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.)
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.)
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">
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.)
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.)
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.)
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.)
182 If <literal>FOR UPDATE</literal> or <literal>FOR SHARE</literal>
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.)
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).
202 <title>Parameters</title>
204 <refsect2 id="SQL-WITH">
205 <title id="sql-with-title"><literal>WITH</literal> Clause</title>
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.
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.
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
237 <replaceable class="parameter">non_recursive_term</replaceable> UNION [ ALL | DISTINCT ] <replaceable class="parameter">recursive_term</replaceable>
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
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.
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.
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.
277 See <xref linkend="queries-with"> for additional information.
281 <refsect2 id="SQL-FROM">
282 <title id="sql-from-title"><literal>FROM</literal> Clause</title>
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
294 The <literal>FROM</literal> clause can contain the following
299 <term><replaceable class="parameter">table_name</replaceable></term>
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.
311 <term><replaceable class="parameter">alias</replaceable></term>
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.
329 <term><replaceable class="parameter">select</replaceable></term>
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
339 <xref linkend="sql-values"> command
340 can also be used here.
346 <term><replaceable class="parameter">with_query_name</replaceable></term>
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
355 An alias can be provided in the same way as for a table.
361 <term><replaceable class="parameter">function_name</replaceable></term>
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.
385 <term><replaceable class="parameter">join_type</replaceable></term>
391 <para><literal>[ INNER ] JOIN</literal></para>
394 <para><literal>LEFT [ OUTER ] JOIN</literal></para>
397 <para><literal>RIGHT [ OUTER ] JOIN</literal></para>
400 <para><literal>FULL [ OUTER ] JOIN</literal></para>
403 <para><literal>CROSS JOIN</literal></para>
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.
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.
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
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.
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.
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).
468 <term><literal>ON <replaceable class="parameter">join_condition</replaceable></literal></term>
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
481 <term><literal>USING ( <replaceable class="parameter">join_column</replaceable> [, ...] )</literal></term>
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
495 <term><literal>NATURAL</literal></term>
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.
508 <refsect2 id="SQL-WHERE">
509 <title id="sql-where-title"><literal>WHERE</literal> Clause</title>
512 The optional <literal>WHERE</literal> clause has the general form
514 WHERE <replaceable class="parameter">condition</replaceable>
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.
525 <refsect2 id="SQL-GROUPBY">
526 <title id="sql-groupby-title"><literal>GROUP BY</literal> Clause</title>
529 The optional <literal>GROUP BY</literal> clause has the general form
531 GROUP BY <replaceable class="parameter">expression</replaceable> [, ...]
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.
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.
563 <refsect2 id="SQL-HAVING">
564 <title id="sql-having-title"><literal>HAVING</literal> Clause</title>
567 The optional <literal>HAVING</literal> clause has the general form
569 HAVING <replaceable class="parameter">condition</replaceable>
571 where <replaceable class="parameter">condition</replaceable> is
572 the same as specified for the <literal>WHERE</literal> clause.
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.
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.
599 <refsect2 id="SQL-WINDOW">
600 <title id="sql-window-title"><literal>WINDOW</literal> Clause</title>
603 The optional <literal>WINDOW</literal> clause has the general form
605 WINDOW <replaceable class="parameter">window_name</replaceable> AS ( <replaceable class="parameter">window_definition</replaceable> ) [, ...]
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
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> ]
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.
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
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
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.
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
658 [ RANGE | ROWS ] <replaceable>frame_start</>
659 [ RANGE | ROWS ] BETWEEN <replaceable>frame_start</> AND <replaceable>frame_end</>
662 where <replaceable>frame_start</> and <replaceable>frame_end</> can be
667 <replaceable>value</replaceable> PRECEDING
669 <replaceable>value</replaceable> FOLLOWING
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 — for example
679 <literal>RANGE BETWEEN CURRENT ROW AND <replaceable>value</>
680 PRECEDING</literal> is not allowed.
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.
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.
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.
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">.
739 <refsect2 id="sql-select-list">
740 <title id="sql-select-list-title"><command>SELECT</command> List</title>
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.
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.
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.
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.
789 <refsect2 id="sql-distinct">
790 <title id="sql-distinct-title"><literal>DISTINCT</literal> Clause</title>
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.
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
810 SELECT DISTINCT ON (location) location, time, report
812 ORDER BY location, time DESC;
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.
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.
828 <refsect2 id="SQL-UNION">
829 <title id="sql-union-title"><literal>UNION</literal> Clause</title>
832 The <literal>UNION</literal> clause has this general form:
834 <replaceable class="parameter">select_statement</replaceable> UNION [ ALL | DISTINCT ] <replaceable class="parameter">select_statement</replaceable>
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
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
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.
869 Multiple <literal>UNION</> operators in the same
870 <command>SELECT</command> statement are evaluated left to right,
871 unless otherwise indicated by parentheses.
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
881 <refsect2 id="SQL-INTERSECT">
882 <title id="sql-intersect-title"><literal>INTERSECT</literal> Clause</title>
885 The <literal>INTERSECT</literal> clause has this general form:
887 <replaceable class="parameter">select_statement</replaceable> INTERSECT [ ALL | DISTINCT ] <replaceable class="parameter">select_statement</replaceable>
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.
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.
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.
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
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</>.
929 <refsect2 id="SQL-EXCEPT">
930 <title id="sql-except-title"><literal>EXCEPT</literal> Clause</title>
933 The <literal>EXCEPT</literal> clause has this general form:
935 <replaceable class="parameter">select_statement</replaceable> EXCEPT [ ALL | DISTINCT ] <replaceable class="parameter">select_statement</replaceable>
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.
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.
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.
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</>.
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</>.
973 <refsect2 id="SQL-ORDERBY">
974 <title id="sql-orderby-title"><literal>ORDER BY</literal> Clause</title>
977 The optional <literal>ORDER BY</literal> clause has this general form:
979 ORDER BY <replaceable class="parameter">expression</replaceable> [ ASC | DESC | USING <replaceable class="parameter">operator</replaceable> ] [ NULLS { FIRST | LAST } ] [, ...]
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.
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.
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.
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:
1011 SELECT name FROM distributors ORDER BY code;
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.
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.
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 <</> and
1037 <literal>DESC</> is usually equivalent to <literal>USING ></>.
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
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.
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</>.
1061 Character-string data is sorted according to the locale-specific
1062 collation order that was established when the database was created.
1066 <refsect2 id="SQL-LIMIT">
1067 <title id="sql-limit-title"><literal>LIMIT</literal> Clause</title>
1070 The <literal>LIMIT</literal> clause consists of two independent
1073 LIMIT { <replaceable class="parameter">count</replaceable> | ALL }
1074 OFFSET <replaceable class="parameter">start</replaceable>
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.
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</>.
1093 SQL:2008 introduced a different syntax to achieve the same thing,
1094 which <productname>PostgreSQL</> also supports. It is:
1096 OFFSET <replaceable class="parameter">start</replaceable> { ROW | ROWS }
1097 FETCH { FIRST | NEXT } [ <replaceable class="parameter">count</replaceable> ] { ROW | ROWS } ONLY
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.
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 — 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</>.
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.
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.
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>
1148 The <literal>FOR UPDATE</literal> clause has this form:
1150 FOR UPDATE [ OF <replaceable class="parameter">table_name</replaceable> [, ...] ] [ NOWAIT ]
1155 The closely related <literal>FOR SHARE</literal> clause has this form:
1157 FOR SHARE [ OF <replaceable class="parameter">table_name</replaceable> [, ...] ] [ NOWAIT ]
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
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>.
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) — 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.
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.
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
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.
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.
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,
1261 SELECT * FROM (SELECT * FROM mytable FOR UPDATE) ss WHERE col1 = 5;
1263 will lock only rows having <literal>col1 = 5</>, even though that
1264 condition is not textually within the sub-query.
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:
1274 SELECT * FROM mytable WHERE key = 1 FOR UPDATE;
1276 UPDATE mytable SET ... WHERE key = 1;
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>.
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,
1304 SELECT * FROM (SELECT * FROM mytable FOR UPDATE) ss ORDER BY column1;
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.
1317 <refsect2 id="SQL-TABLE">
1318 <title><literal>TABLE</literal> Command</title>
1323 TABLE <replaceable class="parameter">name</replaceable>
1325 is completely equivalent to
1327 SELECT * FROM <replaceable class="parameter">name</replaceable>
1329 It can be used as a top-level command or as a space-saving syntax
1330 variant in parts of complex queries.
1336 <title>Examples</title>
1339 To join the table <literal>films</literal> with the table
1340 <literal>distributors</literal>:
1343 SELECT f.title, f.did, d.name, f.date_prod, f.kind
1344 FROM distributors d, films f
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
1356 To sum the column <literal>len</literal> of all films and group
1357 the results by <literal>kind</literal>:
1360 SELECT kind, sum(len) AS total FROM films GROUP BY kind;
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:
1378 SELECT kind, sum(len) AS total
1381 HAVING sum(len) < interval '5 hours';
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>):
1396 SELECT * FROM distributors ORDER BY name;
1397 SELECT * FROM distributors ORDER BY 2;
1400 -----+------------------
1401 109 | 20th Century Fox
1402 110 | Bavaria Atelier
1405 102 | Jean Luc Godard
1410 105 | United Artists
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.
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
1433 SELECT distributors.name
1435 WHERE distributors.name LIKE 'W%'
1439 WHERE actors.name LIKE 'W%';
1453 This example shows how to use a function in the <literal>FROM</>
1454 clause, both with and without a column definition list:
1457 CREATE FUNCTION distributors(int) RETURNS SETOF distributors AS $$
1458 SELECT * FROM distributors WHERE did = $1;
1461 SELECT * FROM distributors(111);
1466 CREATE FUNCTION distributors_2(int) RETURNS SETOF record AS $$
1467 SELECT * FROM distributors WHERE did = $1;
1470 SELECT * FROM distributors_2(111) AS (f1 int, f2 text);
1478 This example shows how to use a simple <literal>WITH</> clause:
1482 SELECT random() as x FROM generate_series(1, 3)
1489 --------------------
1498 Notice that the <literal>WITH</> query was evaluated only once,
1499 so that we got two sets of the same three random values.
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
1509 WITH RECURSIVE employee_recursive(distance, employee_name, manager_name) AS (
1510 SELECT 1, employee_name, manager_name
1512 WHERE manager_name = 'Mary'
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
1518 SELECT distance, employee_name FROM employee_recursive;
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">
1531 <title>Compatibility</title>
1534 Of course, the <command>SELECT</command> statement is compatible
1535 with the SQL standard. But there are some extensions and some
1540 <title>Omitted <literal>FROM</literal> Clauses</title>
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:
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>.
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:
1563 SELECT distributors.* WHERE distributors.name = 'Westward';
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.
1573 <title>Omitting the <literal>AS</literal> Key Word</title>
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.
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
1596 <title><literal>ONLY</literal> and Parentheses</title>
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>
1609 <title>Namespace Available to <literal>GROUP BY</literal> and <literal>ORDER BY</literal></title>
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.
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.
1634 <title>Functional Dependencies</title>
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
1646 <title><literal>WINDOW</literal> Clause Restrictions</title>
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.
1657 <title><literal>LIMIT</literal> and <literal>OFFSET</literal></title>
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.)
1675 <title><literal>FOR UPDATE</> and <literal>FOR SHARE</></title>
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.
1688 <title>Data-Modifying Statements in <literal>WITH</></title>
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.
1698 <title>Nonstandard Clauses</title>
1701 The clause <literal>DISTINCT ON</literal> is not defined in the