2 $PostgreSQL: pgsql/doc/src/sgml/ref/select.sgml,v 1.82 2005/03/10 23:21:20 tgl Exp $
3 PostgreSQL documentation
6 <refentry id="SQL-SELECT">
8 <refentrytitle id="sql-select-title">SELECT</refentrytitle>
9 <refmiscinfo>SQL - Language Statements</refmiscinfo>
13 <refname>SELECT</refname>
14 <refpurpose>retrieve rows from a table or view</refpurpose>
17 <indexterm zone="sql-select">
18 <primary>SELECT</primary>
23 SELECT [ ALL | DISTINCT [ ON ( <replaceable class="parameter">expression</replaceable> [, ...] ) ] ]
24 * | <replaceable class="parameter">expression</replaceable> [ AS <replaceable class="parameter">output_name</replaceable> ] [, ...]
25 [ FROM <replaceable class="parameter">from_item</replaceable> [, ...] ]
26 [ WHERE <replaceable class="parameter">condition</replaceable> ]
27 [ GROUP BY <replaceable class="parameter">expression</replaceable> [, ...] ]
28 [ HAVING <replaceable class="parameter">condition</replaceable> [, ...] ]
29 [ { UNION | INTERSECT | EXCEPT } [ ALL ] <replaceable class="parameter">select</replaceable> ]
30 [ ORDER BY <replaceable class="parameter">expression</replaceable> [ ASC | DESC | USING <replaceable class="parameter">operator</replaceable> ] [, ...] ]
31 [ LIMIT { <replaceable class="parameter">count</replaceable> | ALL } ]
32 [ OFFSET <replaceable class="parameter">start</replaceable> ]
33 [ FOR UPDATE [ OF <replaceable class="parameter">table_name</replaceable> [, ...] ] ]
35 where <replaceable class="parameter">from_item</replaceable> can be one of:
37 [ ONLY ] <replaceable class="parameter">table_name</replaceable> [ * ] [ [ AS ] <replaceable class="parameter">alias</replaceable> [ ( <replaceable class="parameter">column_alias</replaceable> [, ...] ) ] ]
38 ( <replaceable class="parameter">select</replaceable> ) [ AS ] <replaceable class="parameter">alias</replaceable> [ ( <replaceable class="parameter">column_alias</replaceable> [, ...] ) ]
39 <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> [, ...] ) ]
40 <replaceable class="parameter">function_name</replaceable> ( [ <replaceable class="parameter">argument</replaceable> [, ...] ] ) AS ( <replaceable class="parameter">column_definition</replaceable> [, ...] )
41 <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> [, ...] ) ]
47 <title>Description</title>
50 <command>SELECT</command> retrieves rows from one or more tables.
51 The general processing of <command>SELECT</command> is as follows:
56 All elements in the <literal>FROM</literal> list are computed.
57 (Each element in the <literal>FROM</literal> list is a real or
58 virtual table.) If more than one element is specified in the
59 <literal>FROM</literal> list, they are cross-joined together.
60 (See <xref linkend="sql-from" endterm="sql-from-title"> below.)
66 If the <literal>WHERE</literal> clause is specified, all rows
67 that do not satisfy the condition are eliminated from the
68 output. (See <xref linkend="sql-where"
69 endterm="sql-where-title"> below.)
75 If the <literal>GROUP BY</literal> clause is specified, the
76 output is divided into groups of rows that match on one or more
77 values. If the <literal>HAVING</literal> clause is present, it
78 eliminates groups that do not satisfy the given condition. (See
79 <xref linkend="sql-groupby" endterm="sql-groupby-title"> and
80 <xref linkend="sql-having" endterm="sql-having-title"> below.)
86 The actual output rows are computed using the
87 <command>SELECT</command> output expressions for each selected
89 <xref linkend="sql-select-list" endterm="sql-select-list-title">
96 Using the operators <literal>UNION</literal>,
97 <literal>INTERSECT</literal>, and <literal>EXCEPT</literal>, the
98 output of more than one <command>SELECT</command> statement can
99 be combined to form a single result set. The
100 <literal>UNION</literal> operator returns all rows that are in
101 one or both of the result sets. The
102 <literal>INTERSECT</literal> operator returns all rows that are
103 strictly in both result sets. The <literal>EXCEPT</literal>
104 operator returns the rows that are in the first result set but
105 not in the second. In all three cases, duplicate rows are
106 eliminated unless <literal>ALL</literal> is specified. (See
107 <xref linkend="sql-union" endterm="sql-union-title">, <xref
108 linkend="sql-intersect" endterm="sql-intersect-title">, and
109 <xref linkend="sql-except" endterm="sql-except-title"> below.)
115 If the <literal>ORDER BY</literal> clause is specified, the
116 returned rows are sorted in the specified order. If
117 <literal>ORDER BY</literal> is not given, the rows are returned
118 in whatever order the system finds fastest to produce. (See
119 <xref linkend="sql-orderby" endterm="sql-orderby-title"> below.)
125 <literal>DISTINCT</literal> eliminates duplicate rows from the
126 result. <literal>DISTINCT ON</literal> eliminates rows that
127 match on all the specified expressions. <literal>ALL</literal>
128 (the default) will return all candidate rows, including
129 duplicates. (See <xref linkend="sql-distinct"
130 endterm="sql-distinct-title"> below.)
136 If the <literal>LIMIT</literal> or <literal>OFFSET</literal>
137 clause is specified, the <command>SELECT</command> statement
138 only returns a subset of the result rows. (See <xref
139 linkend="sql-limit" endterm="sql-limit-title"> below.)
145 The <literal>FOR UPDATE</literal> clause causes the
146 <command>SELECT</command> statement to lock the selected rows
147 against concurrent updates. (See <xref linkend="sql-for-update"
148 endterm="sql-for-update-title"> below.)
155 You must have <literal>SELECT</literal> privilege on a table to
156 read its values. The use of <literal>FOR UPDATE</literal> requires
157 <literal>UPDATE</literal> privilege as well.
162 <title>Parameters</title>
164 <refsect2 id="SQL-FROM">
165 <title id="sql-from-title"><literal>FROM</literal> Clause</title>
168 The <literal>FROM</literal> clause specifies one or more source
169 tables for the <command>SELECT</command>. If multiple sources are
170 specified, the result is the Cartesian product (cross join) of all
171 the sources. But usually qualification conditions
172 are added to restrict the returned rows to a small subset of the
177 The <literal>FROM</literal> clause can contain the following
182 <term><replaceable class="parameter">table_name</replaceable></term>
185 The name (optionally schema-qualified) of an existing table or
186 view. If <literal>ONLY</> is specified, only that table is
187 scanned. If <literal>ONLY</> is not specified, the table and
188 all its descendant tables (if any) are scanned. <literal>*</>
189 can be appended to the table name to indicate that descendant
190 tables are to be scanned, but in the current version, this is
191 the default behavior. (In releases before 7.1,
192 <literal>ONLY</> was the default behavior.) The default
193 behavior can be modified by changing the <xref
194 linkend="guc-sql-inheritance"> configuration option.
200 <term><replaceable class="parameter">alias</replaceable></term>
203 A substitute name for the <literal>FROM</> item containing the
204 alias. An alias is used for brevity or to eliminate ambiguity
205 for self-joins (where the same table is scanned multiple
206 times). When an alias is provided, it completely hides the
207 actual name of the table or function; for example given
208 <literal>FROM foo AS f</>, the remainder of the
209 <command>SELECT</command> must refer to this <literal>FROM</>
210 item as <literal>f</> not <literal>foo</>. If an alias is
211 written, a column alias list can also be written to provide
212 substitute names for one or more columns of the table.
218 <term><replaceable class="parameter">select</replaceable></term>
221 A sub-<command>SELECT</command> can appear in the
222 <literal>FROM</literal> clause. This acts as though its
223 output were created as a temporary table for the duration of
224 this single <command>SELECT</command> command. Note that the
225 sub-<command>SELECT</command> must be surrounded by
226 parentheses, and an alias <emphasis>must</emphasis> be
233 <term><replaceable class="parameter">function_name</replaceable></term>
236 Function calls can appear in the <literal>FROM</literal>
237 clause. (This is especially useful for functions that return
238 result sets, but any function can be used.) This acts as
239 though its output were created as a temporary table for the
240 duration of this single <command>SELECT</command> command. An
241 alias may also be used. If an alias is written, a column alias
242 list can also be written to provide substitute names for one
243 or more attributes of the function's composite return type. If
244 the function has been defined as returning the <type>record</>
245 data type, then an alias or the key word <literal>AS</> must
246 be present, followed by a column definition list in the form
247 <literal>( <replaceable
248 class="parameter">column_name</replaceable> <replaceable
249 class="parameter">data_type</replaceable> <optional>, ... </>
250 )</literal>. The column definition list must match the actual
251 number and types of columns returned by the function.
257 <term><replaceable class="parameter">join_type</replaceable></term>
263 <para><literal>[ INNER ] JOIN</literal></para>
266 <para><literal>LEFT [ OUTER ] JOIN</literal></para>
269 <para><literal>RIGHT [ OUTER ] JOIN</literal></para>
272 <para><literal>FULL [ OUTER ] JOIN</literal></para>
275 <para><literal>CROSS JOIN</literal></para>
279 For the <literal>INNER</> and <literal>OUTER</> join types, a
280 join condition must be specified, namely exactly one of
281 <literal>NATURAL</>, <literal>ON <replaceable
282 class="parameter">join_condition</replaceable></literal>, or
283 <literal>USING (<replaceable
284 class="parameter">join_column</replaceable> [, ...])</literal>.
285 See below for the meaning. For <literal>CROSS JOIN</literal>,
286 none of these clauses may appear.
290 A <literal>JOIN</literal> clause combines two
291 <literal>FROM</> items. Use parentheses if necessary to
292 determine the order of nesting. In the absence of parentheses,
293 <literal>JOIN</literal>s nest left-to-right. In any case
294 <literal>JOIN</literal> binds more tightly than the commas
295 separating <literal>FROM</> items.
299 <literal>CROSS JOIN</> and <literal>INNER JOIN</literal>
300 produce a simple Cartesian product, the same result as you get from
301 listing the two items at the top level of <literal>FROM</>,
302 but restricted by the join condition (if any).
303 <literal>CROSS JOIN</> is equivalent to <literal>INNER JOIN ON
304 (TRUE)</>, that is, no rows are removed by qualification.
305 These join types are just a notational convenience, since they
306 do nothing you couldn't do with plain <literal>FROM</> and
311 <literal>LEFT OUTER JOIN</> returns all rows in the qualified
312 Cartesian product (i.e., all combined rows that pass its join
313 condition), plus one copy of each row in the left-hand table
314 for which there was no right-hand row that passed the join
315 condition. This left-hand row is extended to the full width
316 of the joined table by inserting null values for the
317 right-hand columns. Note that only the <literal>JOIN</>
318 clause's own condition is considered while deciding which rows
319 have matches. Outer conditions are applied afterwards.
323 Conversely, <literal>RIGHT OUTER JOIN</> returns all the
324 joined rows, plus one row for each unmatched right-hand row
325 (extended with nulls on the left). This is just a notational
326 convenience, since you could convert it to a <literal>LEFT
327 OUTER JOIN</> by switching the left and right inputs.
331 <literal>FULL OUTER JOIN</> returns all the joined rows, plus
332 one row for each unmatched left-hand row (extended with nulls
333 on the right), plus one row for each unmatched right-hand row
334 (extended with nulls on the left).
340 <term><literal>ON <replaceable class="parameter">join_condition</replaceable></literal></term>
343 <replaceable class="parameter">join_condition</replaceable> is
344 an expression resulting in a value of type
345 <type>boolean</type> (similar to a <literal>WHERE</literal>
346 clause) that specifies which rows in a join are considered to
353 <term><literal>USING (<replaceable class="parameter">join_column</replaceable> [, ...])</literal></term>
356 A clause of the form <literal>USING ( a, b, ... )</literal> is
357 shorthand for <literal>ON left_table.a = right_table.a AND
358 left_table.b = right_table.b ...</literal>. Also,
359 <literal>USING</> implies that only one of each pair of
360 equivalent columns will be included in the join output, not
367 <term><literal>NATURAL</literal></term>
370 <literal>NATURAL</literal> is shorthand for a
371 <literal>USING</> list that mentions all columns in the two
372 tables that have the same names.
380 <refsect2 id="SQL-WHERE">
381 <title id="sql-where-title"><literal>WHERE</literal> Clause</title>
384 The optional <literal>WHERE</literal> clause has the general form
386 WHERE <replaceable class="parameter">condition</replaceable>
388 where <replaceable class="parameter">condition</replaceable> is
389 any expression that evaluates to a result of type
390 <type>boolean</type>. Any row that does not satisfy this
391 condition will be eliminated from the output. A row satisfies the
392 condition if it returns true when the actual row values are
393 substituted for any variable references.
397 <refsect2 id="SQL-GROUPBY">
398 <title id="sql-groupby-title"><literal>GROUP BY</literal> Clause</title>
401 The optional <literal>GROUP BY</literal> clause has the general form
403 GROUP BY <replaceable class="parameter">expression</replaceable> [, ...]
408 <literal>GROUP BY</literal> will condense into a single row all
409 selected rows that share the same values for the grouped
410 expressions. <replaceable
411 class="parameter">expression</replaceable> can be an input column
412 name, or the name or ordinal number of an output column
413 (<command>SELECT</command> list item), or an arbitrary
414 expression formed from input-column values. In case of ambiguity,
415 a <literal>GROUP BY</literal> name will be interpreted as an
416 input-column name rather than an output column name.
420 Aggregate functions, if any are used, are computed across all rows
421 making up each group, producing a separate value for each group
422 (whereas without <literal>GROUP BY</literal>, an aggregate
423 produces a single value computed across all the selected rows).
424 When <literal>GROUP BY</literal> is present, it is not valid for
425 the <command>SELECT</command> list expressions to refer to
426 ungrouped columns except within aggregate functions, since there
427 would be more than one possible value to return for an ungrouped
432 <refsect2 id="SQL-HAVING">
433 <title id="sql-having-title"><literal>HAVING</literal> Clause</title>
436 The optional <literal>HAVING</literal> clause has the general form
438 HAVING <replaceable class="parameter">condition</replaceable>
440 where <replaceable class="parameter">condition</replaceable> is
441 the same as specified for the <literal>WHERE</literal> clause.
445 <literal>HAVING</literal> eliminates group rows that do not
446 satisfy the condition. <literal>HAVING</literal> is different
447 from <literal>WHERE</literal>: <literal>WHERE</literal> filters
448 individual rows before the application of <literal>GROUP
449 BY</literal>, while <literal>HAVING</literal> filters group rows
450 created by <literal>GROUP BY</literal>. Each column referenced in
451 <replaceable class="parameter">condition</replaceable> must
452 unambiguously reference a grouping column, unless the reference
453 appears within an aggregate function.
457 The presence of <literal>HAVING</literal> turns a query into a grouped
458 query even if there is no <literal>GROUP BY</> clause. This is the
459 same as what happens when the query contains aggregate functions but
460 no <literal>GROUP BY</> clause. All the selected rows are considered to
461 form a single group, and the <command>SELECT</command> list and
462 <literal>HAVING</literal> clause can only reference table columns from
463 within aggregate functions. Such a query will emit a single row if the
464 <literal>HAVING</literal> condition is true, zero rows if it is not true.
468 <refsect2 id="sql-select-list">
469 <title id="sql-select-list-title"><command>SELECT</command> List</title>
472 The <command>SELECT</command> list (between the key words
473 <literal>SELECT</> and <literal>FROM</>) specifies expressions
474 that form the output rows of the <command>SELECT</command>
475 statement. The expressions can (and usually do) refer to columns
476 computed in the <literal>FROM</> clause. Using the clause
477 <literal>AS <replaceable
478 class="parameter">output_name</replaceable></literal>, another
479 name can be specified for an output column. This name is
480 primarily used to label the column for display. It can also be
481 used to refer to the column's value in <literal>ORDER BY</> and
482 <literal>GROUP BY</> clauses, but not in the <literal>WHERE</> or
483 <literal>HAVING</> clauses; there you must write out the
488 Instead of an expression, <literal>*</literal> can be written in
489 the output list as a shorthand for all the columns of the selected
490 rows. Also, one can write <literal><replaceable
491 class="parameter">table_name</replaceable>.*</literal> as a
492 shorthand for the columns coming from just that table.
496 <refsect2 id="SQL-UNION">
497 <title id="sql-union-title"><literal>UNION</literal> Clause</title>
500 The <literal>UNION</literal> clause has this general form:
502 <replaceable class="parameter">select_statement</replaceable> UNION [ ALL ] <replaceable class="parameter">select_statement</replaceable>
504 <replaceable class="parameter">select_statement</replaceable> is
505 any <command>SELECT</command> statement without an <literal>ORDER
506 BY</>, <literal>LIMIT</>, or <literal>FOR UPDATE</literal> clause.
507 (<literal>ORDER BY</> and <literal>LIMIT</> can be attached to a
508 subexpression if it is enclosed in parentheses. Without
509 parentheses, these clauses will be taken to apply to the result of
510 the <literal>UNION</literal>, not to its right-hand input
515 The <literal>UNION</literal> operator computes the set union of
516 the rows returned by the involved <command>SELECT</command>
517 statements. A row is in the set union of two result sets if it
518 appears in at least one of the result sets. The two
519 <command>SELECT</command> statements that represent the direct
520 operands of the <literal>UNION</literal> must produce the same
521 number of columns, and corresponding columns must be of compatible
526 The result of <literal>UNION</> does not contain any duplicate
527 rows unless the <literal>ALL</> option is specified.
528 <literal>ALL</> prevents elimination of duplicates. (Therefore,
529 <literal>UNION ALL</> is usually significantly quicker than
530 <literal>UNION</>; use <literal>ALL</> when you can.)
534 Multiple <literal>UNION</> operators in the same
535 <command>SELECT</command> statement are evaluated left to right,
536 unless otherwise indicated by parentheses.
540 Currently, <literal>FOR UPDATE</> may not be specified either for
541 a <literal>UNION</> result or for any input of a <literal>UNION</>.
545 <refsect2 id="SQL-INTERSECT">
546 <title id="sql-intersect-title"><literal>INTERSECT</literal> Clause</title>
549 The <literal>INTERSECT</literal> clause has this general form:
551 <replaceable class="parameter">select_statement</replaceable> INTERSECT [ ALL ] <replaceable class="parameter">select_statement</replaceable>
553 <replaceable class="parameter">select_statement</replaceable> is
554 any <command>SELECT</command> statement without an <literal>ORDER
555 BY</>, <literal>LIMIT</>, or <literal>FOR UPDATE</literal> clause.
559 The <literal>INTERSECT</literal> operator computes the set
560 intersection of the rows returned by the involved
561 <command>SELECT</command> statements. A row is in the
562 intersection of two result sets if it appears in both result sets.
566 The result of <literal>INTERSECT</literal> does not contain any
567 duplicate rows unless the <literal>ALL</> option is specified.
568 With <literal>ALL</>, a row that has <replaceable>m</> duplicates in the
569 left table and <replaceable>n</> duplicates in the right table will appear
570 min(<replaceable>m</>,<replaceable>n</>) times in the result set.
574 Multiple <literal>INTERSECT</literal> operators in the same
575 <command>SELECT</command> statement are evaluated left to right,
576 unless parentheses dictate otherwise.
577 <literal>INTERSECT</literal> binds more tightly than
578 <literal>UNION</literal>. That is, <literal>A UNION B INTERSECT
579 C</literal> will be read as <literal>A UNION (B INTERSECT
584 Currently, <literal>FOR UPDATE</> may not be specified either for
585 an <literal>INTERSECT</> result or for any input of an <literal>INTERSECT</>.
589 <refsect2 id="SQL-EXCEPT">
590 <title id="sql-except-title"><literal>EXCEPT</literal> Clause</title>
593 The <literal>EXCEPT</literal> clause has this general form:
595 <replaceable class="parameter">select_statement</replaceable> EXCEPT [ ALL ] <replaceable class="parameter">select_statement</replaceable>
597 <replaceable class="parameter">select_statement</replaceable> is
598 any <command>SELECT</command> statement without an <literal>ORDER
599 BY</>, <literal>LIMIT</>, or <literal>FOR UPDATE</literal> clause.
603 The <literal>EXCEPT</literal> operator computes the set of rows
604 that are in the result of the left <command>SELECT</command>
605 statement but not in the result of the right one.
609 The result of <literal>EXCEPT</literal> does not contain any
610 duplicate rows unless the <literal>ALL</> option is specified.
611 With <literal>ALL</>, a row that has <replaceable>m</> duplicates in the
612 left table and <replaceable>n</> duplicates in the right table will appear
613 max(<replaceable>m</>-<replaceable>n</>,0) times in the result set.
617 Multiple <literal>EXCEPT</literal> operators in the same
618 <command>SELECT</command> statement are evaluated left to right,
619 unless parentheses dictate otherwise. <literal>EXCEPT</> binds at
620 the same level as <literal>UNION</>.
624 Currently, <literal>FOR UPDATE</> may not be specified either for
625 an <literal>EXCEPT</> result or for any input of an <literal>EXCEPT</>.
629 <refsect2 id="SQL-ORDERBY">
630 <title id="sql-orderby-title"><literal>ORDER BY</literal> Clause</title>
633 The optional <literal>ORDER BY</literal> clause has this general form:
635 ORDER BY <replaceable class="parameter">expression</replaceable> [ ASC | DESC | USING <replaceable class="parameter">operator</replaceable> ] [, ...]
637 <replaceable class="parameter">expression</replaceable> can be the
638 name or ordinal number of an output column
639 (<command>SELECT</command> list item), or it can be an arbitrary
640 expression formed from input-column values.
644 The <literal>ORDER BY</literal> clause causes the result rows to
645 be sorted according to the specified expressions. If two rows are
646 equal according to the leftmost expression, the are compared
647 according to the next expression and so on. If they are equal
648 according to all specified expressions, they are returned in
649 an implementation-dependent order.
653 The ordinal number refers to the ordinal (left-to-right) position
654 of the result column. This feature makes it possible to define an
655 ordering on the basis of a column that does not have a unique
656 name. This is never absolutely necessary because it is always
657 possible to assign a name to a result column using the
658 <literal>AS</> clause.
662 It is also possible to use arbitrary expressions in the
663 <literal>ORDER BY</literal> clause, including columns that do not
664 appear in the <command>SELECT</command> result list. Thus the
665 following statement is valid:
667 SELECT name FROM distributors ORDER BY code;
669 A limitation of this feature is that an <literal>ORDER BY</>
670 clause applying to the result of a <literal>UNION</>,
671 <literal>INTERSECT</>, or <literal>EXCEPT</> clause may only
672 specify an output column name or number, not an expression.
676 If an <literal>ORDER BY</> expression is a simple name that
677 matches both a result column name and an input column name,
678 <literal>ORDER BY</> will interpret it as the result column name.
679 This is the opposite of the choice that <literal>GROUP BY</> will
680 make in the same situation. This inconsistency is made to be
681 compatible with the SQL standard.
685 Optionally one may add the key word <literal>ASC</> (ascending) or
686 <literal>DESC</> (descending) after any expression in the
687 <literal>ORDER BY</> clause. If not specified, <literal>ASC</> is
688 assumed by default. Alternatively, a specific ordering operator
689 name may be specified in the <literal>USING</> clause.
690 <literal>ASC</> is usually equivalent to <literal>USING <</> and
691 <literal>DESC</> is usually equivalent to <literal>USING ></>.
692 (But the creator of a user-defined data type can define exactly what the
693 default sort ordering is, and it might correspond to operators with other
698 The null value sorts higher than any other value. In other words,
699 with ascending sort order, null values sort at the end, and with
700 descending sort order, null values sort at the beginning.
704 Character-string data is sorted according to the locale-specific
705 collation order that was established when the database cluster
710 <refsect2 id="sql-distinct">
711 <title id="sql-distinct-title"><literal>DISTINCT</literal> Clause</title>
714 If <literal>DISTINCT</> is specified, all duplicate rows are
715 removed from the result set (one row is kept from each group of
716 duplicates). <literal>ALL</> specifies the opposite: all rows are
717 kept; that is the default.
721 <literal>DISTINCT ON ( <replaceable
722 class="parameter">expression</replaceable> [, ...] )</literal>
723 keeps only the first row of each set of rows where the given
724 expressions evaluate to equal. The <literal>DISTINCT ON</literal>
725 expressions are interpreted using the same rules as for
726 <literal>ORDER BY</> (see above). Note that the <quote>first
727 row</quote> of each set is unpredictable unless <literal>ORDER
728 BY</> is used to ensure that the desired row appears first. For
731 SELECT DISTINCT ON (location) location, time, report
733 ORDER BY location, time DESC;
735 retrieves the most recent weather report for each location. But
736 if we had not used <literal>ORDER BY</> to force descending order
737 of time values for each location, we'd have gotten a report from
738 an unpredictable time for each location.
742 The <literal>DISTINCT ON</> expression(s) must match the leftmost
743 <literal>ORDER BY</> expression(s). The <literal>ORDER BY</> clause
744 will normally contain additional expression(s) that determine the
745 desired precedence of rows within each <literal>DISTINCT ON</> group.
749 <refsect2 id="SQL-LIMIT">
750 <title id="sql-limit-title"><literal>LIMIT</literal> Clause</title>
753 The <literal>LIMIT</literal> clause consists of two independent
756 LIMIT { <replaceable class="parameter">count</replaceable> | ALL }
757 OFFSET <replaceable class="parameter">start</replaceable>
759 <replaceable class="parameter">count</replaceable> specifies the
760 maximum number of rows to return, while <replaceable
761 class="parameter">start</replaceable> specifies the number of rows
762 to skip before starting to return rows. When both are specified,
763 <replaceable class="parameter">start</replaceable> rows are skipped
764 before starting to count the <replaceable
765 class="parameter">count</replaceable> rows to be returned.
769 When using <literal>LIMIT</>, it is a good idea to use an
770 <literal>ORDER BY</> clause that constrains the result rows into a
771 unique order. Otherwise you will get an unpredictable subset of
772 the query's rows — you may be asking for the tenth through
773 twentieth rows, but tenth through twentieth in what ordering? You
774 don't know what ordering unless you specify <literal>ORDER BY</>.
778 The query planner takes <literal>LIMIT</> into account when
779 generating a query plan, so you are very likely to get different
780 plans (yielding different row orders) depending on what you use
781 for <literal>LIMIT</> and <literal>OFFSET</>. Thus, using
782 different <literal>LIMIT</>/<literal>OFFSET</> values to select
783 different subsets of a query result <emphasis>will give
784 inconsistent results</emphasis> unless you enforce a predictable
785 result ordering with <literal>ORDER BY</>. This is not a bug; it
786 is an inherent consequence of the fact that SQL does not promise
787 to deliver the results of a query in any particular order unless
788 <literal>ORDER BY</> is used to constrain the order.
792 <refsect2 id="SQL-FOR-UPDATE">
793 <title id="sql-for-update-title"><literal>FOR UPDATE</literal> Clause</title>
796 The <literal>FOR UPDATE</literal> clause has this form:
798 FOR UPDATE [ OF <replaceable class="parameter">table_name</replaceable> [, ...] ]
803 <literal>FOR UPDATE</literal> causes the rows retrieved by the
804 <command>SELECT</command> statement to be locked as though for
805 update. This prevents them from being modified or deleted by
806 other transactions until the current transaction ends. That is,
807 other transactions that attempt <command>UPDATE</command>,
808 <command>DELETE</command>, or <command>SELECT FOR UPDATE</command>
809 of these rows will be blocked until the current transaction ends.
810 Also, if an <command>UPDATE</command>, <command>DELETE</command>,
811 or <command>SELECT FOR UPDATE</command> from another transaction
812 has already locked a selected row or rows, <command>SELECT FOR
813 UPDATE</command> will wait for the other transaction to complete,
814 and will then lock and return the updated row (or no row, if the
815 row was deleted). For further discussion see <xref
820 If specific tables are named in <literal>FOR UPDATE</literal>,
821 then only rows coming from those tables are locked; any other
822 tables used in the <command>SELECT</command> are simply read as
827 <literal>FOR UPDATE</literal> cannot be used in contexts where
828 returned rows can't be clearly identified with individual table
829 rows; for example it can't be used with aggregation.
833 <literal>FOR UPDATE</literal> may appear before
834 <literal>LIMIT</literal> for compatibility with
835 <productname>PostgreSQL</productname> versions before 7.3. It
836 effectively executes after <literal>LIMIT</literal>, however, and
837 so that is the recommended place to write it.
843 <title>Examples</title>
846 To join the table <literal>films</literal> with the table
847 <literal>distributors</literal>:
850 SELECT f.title, f.did, d.name, f.date_prod, f.kind
851 FROM distributors d, films f
854 title | did | name | date_prod | kind
855 -------------------+-----+--------------+------------+----------
856 The Third Man | 101 | British Lion | 1949-12-23 | Drama
857 The African Queen | 101 | British Lion | 1951-08-11 | Romantic
863 To sum the column <literal>len</literal> of all films and group
864 the results by <literal>kind</literal>:
867 SELECT kind, sum(len) AS total FROM films GROUP BY kind;
880 To sum the column <literal>len</literal> of all films, group
881 the results by <literal>kind</literal> and show those group totals
882 that are less than 5 hours:
885 SELECT kind, sum(len) AS total
888 HAVING sum(len) < interval '5 hours';
898 The following two examples are identical ways of sorting the individual
899 results according to the contents of the second column
900 (<literal>name</literal>):
903 SELECT * FROM distributors ORDER BY name;
904 SELECT * FROM distributors ORDER BY 2;
907 -----+------------------
908 109 | 20th Century Fox
909 110 | Bavaria Atelier
912 102 | Jean Luc Godard
925 The next example shows how to obtain the union of the tables
926 <literal>distributors</literal> and
927 <literal>actors</literal>, restricting the results to those that begin
928 with the letter W in each table. Only distinct rows are wanted, so the
929 key word <literal>ALL</literal> is omitted.
932 distributors: actors:
934 -----+-------------- ----+----------------
935 108 | Westward 1 | Woody Allen
936 111 | Walt Disney 2 | Warren Beatty
937 112 | Warner Bros. 3 | Walter Matthau
940 SELECT distributors.name
942 WHERE distributors.name LIKE 'W%'
946 WHERE actors.name LIKE 'W%';
960 This example shows how to use a function in the <literal>FROM</>
961 clause, both with and without a column definition list:
964 CREATE FUNCTION distributors(int) RETURNS SETOF distributors AS $$
965 SELECT * FROM distributors WHERE did = $1;
968 SELECT * FROM distributors(111);
973 CREATE FUNCTION distributors_2(int) RETURNS SETOF record AS $$
974 SELECT * FROM distributors WHERE did = $1;
977 SELECT * FROM distributors_2(111) AS (f1 int, f2 text);
986 <title>Compatibility</title>
989 Of course, the <command>SELECT</command> statement is compatible
990 with the SQL standard. But there are some extensions and some
995 <title>Omitted <literal>FROM</literal> Clauses</title>
998 <productname>PostgreSQL</productname> allows one to omit the
999 <literal>FROM</literal> clause. It has a straightforward use to
1000 compute the results of simple expressions:
1008 Some other <acronym>SQL</acronym> databases cannot do this except
1009 by introducing a dummy one-row table from which to do the
1010 <command>SELECT</command>.
1014 A less obvious use is to abbreviate a normal
1015 <command>SELECT</command> from tables:
1017 SELECT distributors.* WHERE distributors.name = 'Westward';
1023 This works because an implicit <literal>FROM</literal> item is
1024 added for each table that is referenced in other parts of the
1025 <command>SELECT</command> statement but not mentioned in
1026 <literal>FROM</literal>.
1030 While this is a convenient shorthand, it's easy to misuse. For
1031 example, the command
1033 SELECT distributors.* FROM distributors d;
1035 is probably a mistake; most likely the user meant
1037 SELECT d.* FROM distributors d;
1039 rather than the unconstrained join
1041 SELECT distributors.* FROM distributors d, distributors distributors;
1043 that he will actually get. To help detect this sort of mistake,
1044 <productname>PostgreSQL</productname> will warn if the
1045 implicit-<literal>FROM</literal> feature is used in a
1046 <command>SELECT</command> statement that also contains an explicit
1047 <literal>FROM</literal> clause. Also, it is possible to disable
1048 the implicit-<literal>FROM</literal> feature by setting the
1049 <xref linkend="guc-add-missing-from"> parameter to false.
1054 <title>The <literal>AS</literal> Key Word</title>
1057 In the SQL standard, the optional key word <literal>AS</> is just
1058 noise and can be omitted without affecting the meaning. The
1059 <productname>PostgreSQL</productname> parser requires this key
1060 word when renaming output columns because the type extensibility
1061 features lead to parsing ambiguities without it.
1062 <literal>AS</literal> is optional in <literal>FROM</literal>
1068 <title>Namespace Available to <literal>GROUP BY</literal> and <literal>ORDER BY</literal></title>
1071 In the SQL-92 standard, an <literal>ORDER BY</literal> clause may
1072 only use result column names or numbers, while a <literal>GROUP
1073 BY</literal> clause may only use expressions based on input column
1074 names. <productname>PostgreSQL</productname> extends each of
1075 these clauses to allow the other choice as well (but it uses the
1076 standard's interpretation if there is ambiguity).
1077 <productname>PostgreSQL</productname> also allows both clauses to
1078 specify arbitrary expressions. Note that names appearing in an
1079 expression will always be taken as input-column names, not as
1080 result-column names.
1084 SQL:1999 uses a slightly different definition which is not entirely upward
1086 with SQL-92. In most cases, however, <productname>PostgreSQL</productname>
1087 will interpret an <literal>ORDER BY</literal> or <literal>GROUP
1088 BY</literal> expression the same way SQL:1999 does.
1093 <title>Nonstandard Clauses</title>
1096 The clauses <literal>DISTINCT ON</literal>,
1097 <literal>LIMIT</literal>, and <literal>OFFSET</literal> are not
1098 defined in the SQL standard.
1104 <!-- Keep this comment at the end of the file
1109 sgml-minimize-attributes:nil
1110 sgml-always-quote-attributes:t
1113 sgml-parent-document:nil
1114 sgml-default-dtd-file:"../reference.ced"
1115 sgml-exposed-tags:nil
1116 sgml-local-catalogs:"/usr/lib/sgml/catalog"
1117 sgml-local-ecat-files:nil