3 .\" Author: The PostgreSQL Global Development Group
4 .\" Generator: DocBook XSL Stylesheets vsnapshot <http://docbook.sf.net/>
6 .\" Manual: PostgreSQL 18.0 Documentation
7 .\" Source: PostgreSQL 18.0
10 .TH "SELECT" "7" "2025" "PostgreSQL 18.0" "PostgreSQL 18.0 Documentation"
11 .\" -----------------------------------------------------------------
12 .\" * Define some portability stuff
13 .\" -----------------------------------------------------------------
14 .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
15 .\" http://bugs.debian.org/507673
16 .\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html
17 .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
20 .\" -----------------------------------------------------------------
21 .\" * set default formatting
22 .\" -----------------------------------------------------------------
23 .\" disable hyphenation
25 .\" disable justification (adjust text to left margin only)
27 .\" -----------------------------------------------------------------
28 .\" * MAIN CONTENT STARTS HERE *
29 .\" -----------------------------------------------------------------
31 SELECT, TABLE, WITH \- retrieve rows from a table or view
35 [ WITH [ RECURSIVE ] \fIwith_query\fR [, \&.\&.\&.] ]
36 SELECT [ ALL | DISTINCT [ ON ( \fIexpression\fR [, \&.\&.\&.] ) ] ]
37 [ { * | \fIexpression\fR [ [ AS ] \fIoutput_name\fR ] } [, \&.\&.\&.] ]
38 [ FROM \fIfrom_item\fR [, \&.\&.\&.] ]
39 [ WHERE \fIcondition\fR ]
40 [ GROUP BY [ ALL | DISTINCT ] \fIgrouping_element\fR [, \&.\&.\&.] ]
41 [ HAVING \fIcondition\fR ]
42 [ WINDOW \fIwindow_name\fR AS ( \fIwindow_definition\fR ) [, \&.\&.\&.] ]
43 [ { UNION | INTERSECT | EXCEPT } [ ALL | DISTINCT ] \fIselect\fR ]
44 [ ORDER BY \fIexpression\fR [ ASC | DESC | USING \fIoperator\fR ] [ NULLS { FIRST | LAST } ] [, \&.\&.\&.] ]
45 [ LIMIT { \fIcount\fR | ALL } ]
46 [ OFFSET \fIstart\fR [ ROW | ROWS ] ]
47 [ FETCH { FIRST | NEXT } [ \fIcount\fR ] { ROW | ROWS } { ONLY | WITH TIES } ]
48 [ FOR { UPDATE | NO KEY UPDATE | SHARE | KEY SHARE } [ OF \fIfrom_reference\fR [, \&.\&.\&.] ] [ NOWAIT | SKIP LOCKED ] [\&.\&.\&.] ]
50 where \fIfrom_item\fR can be one of:
52 [ ONLY ] \fItable_name\fR [ * ] [ [ AS ] \fIalias\fR [ ( \fIcolumn_alias\fR [, \&.\&.\&.] ) ] ]
53 [ TABLESAMPLE \fIsampling_method\fR ( \fIargument\fR [, \&.\&.\&.] ) [ REPEATABLE ( \fIseed\fR ) ] ]
54 [ LATERAL ] ( \fIselect\fR ) [ [ AS ] \fIalias\fR [ ( \fIcolumn_alias\fR [, \&.\&.\&.] ) ] ]
55 \fIwith_query_name\fR [ [ AS ] \fIalias\fR [ ( \fIcolumn_alias\fR [, \&.\&.\&.] ) ] ]
56 [ LATERAL ] \fIfunction_name\fR ( [ \fIargument\fR [, \&.\&.\&.] ] )
57 [ WITH ORDINALITY ] [ [ AS ] \fIalias\fR [ ( \fIcolumn_alias\fR [, \&.\&.\&.] ) ] ]
58 [ LATERAL ] \fIfunction_name\fR ( [ \fIargument\fR [, \&.\&.\&.] ] ) [ AS ] \fIalias\fR ( \fIcolumn_definition\fR [, \&.\&.\&.] )
59 [ LATERAL ] \fIfunction_name\fR ( [ \fIargument\fR [, \&.\&.\&.] ] ) AS ( \fIcolumn_definition\fR [, \&.\&.\&.] )
60 [ LATERAL ] ROWS FROM( \fIfunction_name\fR ( [ \fIargument\fR [, \&.\&.\&.] ] ) [ AS ( \fIcolumn_definition\fR [, \&.\&.\&.] ) ] [, \&.\&.\&.] )
61 [ WITH ORDINALITY ] [ [ AS ] \fIalias\fR [ ( \fIcolumn_alias\fR [, \&.\&.\&.] ) ] ]
62 \fIfrom_item\fR \fIjoin_type\fR \fIfrom_item\fR { ON \fIjoin_condition\fR | USING ( \fIjoin_column\fR [, \&.\&.\&.] ) [ AS \fIjoin_using_alias\fR ] }
63 \fIfrom_item\fR NATURAL \fIjoin_type\fR \fIfrom_item\fR
64 \fIfrom_item\fR CROSS JOIN \fIfrom_item\fR
66 and \fIgrouping_element\fR can be one of:
70 ( \fIexpression\fR [, \&.\&.\&.] )
71 ROLLUP ( { \fIexpression\fR | ( \fIexpression\fR [, \&.\&.\&.] ) } [, \&.\&.\&.] )
72 CUBE ( { \fIexpression\fR | ( \fIexpression\fR [, \&.\&.\&.] ) } [, \&.\&.\&.] )
73 GROUPING SETS ( \fIgrouping_element\fR [, \&.\&.\&.] )
75 and \fIwith_query\fR is:
77 \fIwith_query_name\fR [ ( \fIcolumn_name\fR [, \&.\&.\&.] ) ] AS [ [ NOT ] MATERIALIZED ] ( \fIselect\fR | \fIvalues\fR | \fIinsert\fR | \fIupdate\fR | \fIdelete\fR | \fImerge\fR )
78 [ SEARCH { BREADTH | DEPTH } FIRST BY \fIcolumn_name\fR [, \&.\&.\&.] SET \fIsearch_seq_col_name\fR ]
79 [ CYCLE \fIcolumn_name\fR [, \&.\&.\&.] SET \fIcycle_mark_col_name\fR [ TO \fIcycle_mark_value\fR DEFAULT \fIcycle_mark_default\fR ] USING \fIcycle_path_col_name\fR ]
81 TABLE [ ONLY ] \fItable_name\fR [ * ]
86 retrieves rows from zero or more tables\&. The general processing of
100 list are computed\&. These effectively serve as temporary tables that can be referenced in the
104 query that is referenced more than once in
106 is computed only once, unless specified otherwise with
107 NOT MATERIALIZED\&. (See
122 list are computed\&. (Each element in the
124 list is a real or virtual table\&.) If more than one element is specified in the
126 list, they are cross\-joined together\&. (See
141 clause is specified, all rows that do not satisfy the condition are eliminated from the output\&. (See
156 clause is specified, or if there are aggregate function calls, the output is combined into groups of rows that match on one or more values, and the results of aggregate functions are computed\&. If the
158 clause is present, it eliminates groups that do not satisfy the given condition\&. (See
162 below\&.) Although query output columns are nominally computed in the next step, they can also be referenced (by name or ordinal number) in the
175 The actual output rows are computed using the
177 output expressions for each selected row or row group\&. (See
191 eliminates duplicate rows from the result\&.
193 eliminates rows that match on all the specified expressions\&.
195 (the default) will return all candidate rows, including duplicates\&. (See
211 EXCEPT, the output of more than one
213 statement can be combined to form a single result set\&. The
215 operator returns all rows that are in one or both of the result sets\&. The
217 operator returns all rows that are strictly in both result sets\&. The
219 operator returns the rows that are in the first result set but not in the second\&. In all three cases, duplicate rows are eliminated unless
221 is specified\&. The noise word
223 can be added to explicitly specify eliminating duplicate rows\&. Notice that
225 is the default behavior here, even though
231 INTERSECT Clause, and
246 clause is specified, the returned rows are sorted in the specified order\&. If
248 is not given, the rows are returned in whatever order the system finds fastest to produce\&. (See
266 clause is specified, the
268 statement only returns a subset of the result rows\&. (See
289 statement locks the selected rows against concurrent updates\&. (See
296 privilege on each column used in a
298 command\&. The use of
306 privilege as well (for at least one column of each table so selected)\&.
312 clause allows you to specify one or more subqueries that can be referenced by name in the primary query\&. The subqueries effectively act as temporary tables or views for the duration of the primary query\&. Each subquery can be a
320 statement\&. When writing a data\-modifying statement (\fBINSERT\fR,
324 WITH, it is usual to include a
326 clause\&. It is the output of
329 the underlying table that the statement modifies, that forms the temporary table that is read by the primary query\&. If
331 is omitted, the statement is still executed, but it produces no output so it cannot be referenced as a table by the primary query\&.
333 A name (without schema qualification) must be specified for each
335 query\&. Optionally, a list of column names can be specified; if this is omitted, the column names are inferred from the subquery\&.
339 is specified, it allows a
341 subquery to reference itself by name\&. Such a subquery must have the form
347 \fInon_recursive_term\fR UNION [ ALL | DISTINCT ] \fIrecursive_term\fR
353 where the recursive self\-reference must appear on the right\-hand side of the
354 UNION\&. Only one recursive self\-reference is permitted per query\&. Recursive data\-modifying statements are not supported, but you can use the results of a recursive
356 query in a data\-modifying statement\&. See
364 queries need not be ordered: a query can reference another one that is later in the list\&. (However, circular references, or mutual recursion, are not implemented\&.) Without
367 queries can only reference sibling
369 queries that are earlier in the
373 When there are multiple queries in the
377 should be written only once, immediately after
378 WITH\&. It applies to all queries in the
380 clause, though it has no effect on queries that do not use recursion or forward references\&.
385 search sequence column
386 that can be used for ordering the results of a recursive query in either breadth\-first or depth\-first order\&. The supplied column name list specifies the row key that is to be used for keeping track of visited rows\&. A column named
387 \fIsearch_seq_col_name\fR
388 will be added to the result column list of the
390 query\&. This column can be ordered by in the outer query to achieve the respective ordering\&. See
396 clause is used to detect cycles in recursive queries\&. The supplied column name list specifies the row key that is to be used for keeping track of visited rows\&. A column named
397 \fIcycle_mark_col_name\fR
398 will be added to the result column list of the
400 query\&. This column will be set to
401 \fIcycle_mark_value\fR
402 when a cycle has been detected, else to
403 \fIcycle_mark_default\fR\&. Furthermore, processing of the recursive union will stop when a cycle has been detected\&.
404 \fIcycle_mark_value\fR
406 \fIcycle_mark_default\fR
407 must be constants and they must be coercible to a common data type, and the data type must have an inequality operator\&. (The SQL standard requires that they be Boolean constants or character strings, but PostgreSQL does not require that\&.) By default,
412 boolean) are used\&. Furthermore, a column named
413 \fIcycle_path_col_name\fR
414 will be added to the result column list of the
416 query\&. This column is used internally for tracking visited rows\&. See
424 clause are only valid for recursive
433 (or equivalent) commands (no nested
434 UNIONs)\&. If both clauses are used, the column added by the
436 clause appears before the columns added by the
440 The primary query and the
442 queries are all (notionally) executed at the same time\&. This implies that the effects of a data\-modifying statement in
444 cannot be seen from other parts of the query, other than by reading its
446 output\&. If two such data\-modifying statements attempt to modify the same row, the results are unspecified\&.
450 queries is that they are normally evaluated only once per execution of the primary query, even if the primary query refers to them more than once\&. In particular, data\-modifying statements are guaranteed to be executed once and only once, regardless of whether the primary query reads all or any of their output\&.
456 to remove this guarantee\&. In that case, the
458 query can be folded into the primary query much as though it were a simple sub\-SELECT
459 in the primary query\*(Aqs
461 clause\&. This results in duplicate computations if the primary query refers to that
463 query more than once; but if each such use requires only a few rows of the
465 query\*(Aqs total output,
467 can provide a net savings by allowing the queries to be optimized jointly\&.
469 is ignored if it is attached to a
471 query that is recursive or is not side\-effect\-free (i\&.e\&., is not a plain
473 containing no volatile functions)\&.
475 By default, a side\-effect\-free
477 query is folded into the primary query if it is used exactly once in the primary query\*(Aqs
479 clause\&. This allows joint optimization of the two query levels in situations where that should be semantically invisible\&. However, such folding can be prevented by marking the
482 MATERIALIZED\&. That might be useful, for example, if the
484 query is being used as an optimization fence to prevent the planner from choosing a bad plan\&.
486 versions before v12 never did such folding, so queries written for older versions might rely on
488 to act as an optimization fence\&.
492 for additional information\&.
497 clause specifies one or more source tables for the
498 \fBSELECT\fR\&. If multiple sources are specified, the result is the Cartesian product (cross join) of all the sources\&. But usually qualification conditions are added (via
499 WHERE) to restrict the returned rows to a small subset of the Cartesian product\&.
503 clause can contain the following elements:
507 The name (optionally schema\-qualified) of an existing table or view\&. If
509 is specified before the table name, only that table is scanned\&. If
511 is not specified, the table and all its descendant tables (if any) are scanned\&. Optionally,
513 can be specified after the table name to explicitly indicate that descendant tables are included\&.
518 A substitute name for the
520 item containing the alias\&. An alias is used for brevity or to eliminate ambiguity for self\-joins (where the same table is scanned multiple times)\&. When an alias is provided, it completely hides the actual name of the table or function; for example given
521 FROM foo AS f, the remainder of the
528 foo\&. If an alias is written, a column alias list can also be written to provide substitute names for one or more columns of the table\&.
531 TABLESAMPLE \fIsampling_method\fR ( \fIargument\fR [, \&.\&.\&.] ) [ REPEATABLE ( \fIseed\fR ) ]
537 indicates that the specified
538 \fIsampling_method\fR
539 should be used to retrieve a subset of the rows in that table\&. This sampling precedes the application of any other filters such as
541 clauses\&. The standard
543 distribution includes two sampling methods,
546 SYSTEM, and other sampling methods can be installed in the database via extensions\&.
552 sampling methods each accept a single
554 which is the fraction of the table to sample, expressed as a percentage between 0 and 100\&. This argument can be any
555 real\-valued expression\&. (Other sampling methods might accept more or different arguments\&.) These two methods each return a randomly\-chosen sample of the table that will contain approximately the specified percentage of the table\*(Aqs rows\&. The
557 method scans the whole table and selects or ignores individual rows independently with the specified probability\&. The
559 method does block\-level sampling with each block having the specified chance of being selected; all rows in each selected block are returned\&. The
561 method is significantly faster than the
563 method when small sampling percentages are specified, but it may return a less\-random sample of the table as a result of clustering effects\&.
569 number or expression to use for generating random numbers within the sampling method\&. The seed value can be any non\-null floating\-point value\&. Two queries that specify the same seed and
571 values will select the same sample of the table, if the table has not been changed meanwhile\&. But different seed values will usually produce different samples\&. If
573 is not given then a new random sample is selected for each query, based upon a system\-generated seed\&. Note that some add\-on sampling methods do not accept
574 REPEATABLE, and will always produce new samples on each use\&.
582 clause\&. This acts as though its output were created as a temporary table for the duration of this single
584 command\&. Note that the sub\-\fBSELECT\fR
585 must be surrounded by parentheses, and an alias can be provided in the same way as for a table\&. A
587 command can also be used here\&.
590 \fIwith_query_name\fR
594 query is referenced by writing its name, just as though the query\*(Aqs name were a table name\&. (In fact, the
596 query hides any real table of the same name for the purposes of the primary query\&. If necessary, you can refer to a real table of the same name by schema\-qualifying the table\*(Aqs name\&.) An alias can be provided in the same way as for a table\&.
601 Function calls can appear in the
603 clause\&. (This is especially useful for functions that return result sets, but any function can be used\&.) This acts as though the function\*(Aqs output were created as a temporary table for the duration of this single
605 command\&. If the function\*(Aqs result type is composite (including the case of a function with multiple
607 parameters), each attribute becomes a separate column in the implicit table\&.
610 \fBWITH ORDINALITY\fR
611 clause is added to the function call, an additional column of type
613 will be appended to the function\*(Aqs result column(s)\&. This column numbers the rows of the function\*(Aqs result set, starting from 1\&. By default, this column is named
616 An alias can be provided in the same way as for a table\&. If an alias is written, a column alias list can also be written to provide substitute names for one or more attributes of the function\*(Aqs composite return type, including the ordinality column if present\&.
618 Multiple function calls can be combined into a single
619 FROM\-clause item by surrounding them with
620 ROWS FROM( \&.\&.\&. )\&. The output of such an item is the concatenation of the first row from each function, then the second row from each function, etc\&. If some of the functions produce fewer rows than others, null values are substituted for the missing data, so that the total number of rows returned is always the same as for the function that produced the most rows\&.
622 If the function has been defined as returning the
624 data type, then an alias or the key word
626 must be present, followed by a column definition list in the form
627 ( \fIcolumn_name\fR \fIdata_type\fR [, \&.\&.\&. ])\&. The column definition list must match the actual number and types of columns returned by the function\&.
630 ROWS FROM( \&.\&.\&. )
631 syntax, if one of the functions requires a column definition list, it\*(Aqs preferred to put the column definition list after the function call inside
632 ROWS FROM( \&.\&.\&. )\&. A column definition list can be placed after the
633 ROWS FROM( \&.\&.\&. )
634 construct only if there\*(Aqs just a single function and no
640 together with a column definition list, you must use the
641 ROWS FROM( \&.\&.\&. )
642 syntax and put the column definition list inside
643 ROWS FROM( \&.\&.\&. )\&.
698 join types, a join condition must be specified, namely exactly one of
699 ON \fIjoin_condition\fR,
700 USING (\fIjoin_column\fR [, \&.\&.\&.]), or
701 NATURAL\&. See below for the meaning\&.
707 items, which for convenience we will refer to as
708 \(lqtables\(rq, though in reality they can be any type of
710 item\&. Use parentheses if necessary to determine the order of nesting\&. In the absence of parentheses,
711 JOINs nest left\-to\-right\&. In any case
713 binds more tightly than the commas separating
714 FROM\-list items\&. All the
716 options are just a notational convenience, since they do nothing you couldn\*(Aqt do with plain
722 returns all rows in the qualified Cartesian product (i\&.e\&., all combined rows that pass its join condition), plus one copy of each row in the left\-hand table for which there was no right\-hand row that passed the join condition\&. This left\-hand row is extended to the full width of the joined table by inserting null values for the right\-hand columns\&. Note that only the
724 clause\*(Aqs own condition is considered while deciding which rows have matches\&. Outer conditions are applied afterwards\&.
728 returns all the joined rows, plus one row for each unmatched right\-hand row (extended with nulls on the left)\&. This is just a notational convenience, since you could convert it to a
730 by switching the left and right tables\&.
733 returns all the joined rows, plus one row for each unmatched left\-hand row (extended with nulls on the right), plus one row for each unmatched right\-hand row (extended with nulls on the left)\&.
736 ON \fIjoin_condition\fR
739 is an expression resulting in a value of type
743 clause) that specifies which rows in a join are considered to match\&.
746 USING ( \fIjoin_column\fR [, \&.\&.\&.] ) [ AS \fIjoin_using_alias\fR ]
749 USING ( a, b, \&.\&.\&. )
751 ON left_table\&.a = right_table\&.a AND left_table\&.b = right_table\&.b \&.\&.\&.\&. Also,
753 implies that only one of each pair of equivalent columns will be included in the join output, not both\&.
756 \fIjoin_using_alias\fR
757 name is specified, it provides a table alias for the join columns\&. Only the join columns listed in the
759 clause are addressable by this name\&. Unlike a regular
760 \fIalias\fR, this does not hide the names of the joined tables from the rest of the query\&. Also unlike a regular
761 \fIalias\fR, you cannot write a column alias list \(em the output names of the join columns are the same as they appear in the
771 list that mentions all columns in the two tables that have matching names\&. If there are no common column names,
781 INNER JOIN ON (TRUE), that is, no rows are removed by qualification\&. They produce a simple Cartesian product, the same result as you get from listing the two tables at the top level of
782 FROM, but restricted by the join condition (if any)\&.
789 key word can precede a sub\-\fBSELECT\fR
791 item\&. This allows the sub\-\fBSELECT\fR
792 to refer to columns of
794 items that appear before it in the
797 LATERAL, each sub\-\fBSELECT\fR
798 is evaluated independently and so cannot cross\-reference any other
803 can also precede a function\-call
805 item, but in this case it is a noise word, because the function expression can refer to earlier
811 item can appear at top level in the
815 tree\&. In the latter case it can also refer to any items that are on the left\-hand side of a
817 that it is on the right\-hand side of\&.
823 cross\-references, evaluation proceeds as follows: for each row of the
825 item providing the cross\-referenced column(s), or set of rows of multiple
827 items providing the columns, the
829 item is evaluated using that row or row set\*(Aqs values of the columns\&. The resulting row(s) are joined as usual with the rows they were computed from\&. This is repeated for each row or set of rows from the column source table(s)\&.
831 The column source table(s) must be
837 item, else there would not be a well\-defined set of rows from which to compute each set of rows for the
839 item\&. Thus, although a construct such as
840 \fIX\fR RIGHT JOIN LATERAL \fIY\fR
841 is syntactically valid, it is not actually allowed for
850 clause has the general form
856 WHERE \fIcondition\fR
864 is any expression that evaluates to a result of type
865 boolean\&. Any row that does not satisfy this condition will be eliminated from the output\&. A row satisfies the condition if it returns true when the actual row values are substituted for any variable references\&.
866 .SS "GROUP BY Clause"
870 clause has the general form
876 GROUP BY [ ALL | DISTINCT ] \fIgrouping_element\fR [, \&.\&.\&.]
883 will condense into a single row all selected rows that share the same values for the grouped expressions\&. An
886 \fIgrouping_element\fR
887 can be an input column name, or the name or ordinal number of an output column (\fBSELECT\fR
888 list item), or an arbitrary expression formed from input\-column values\&. In case of ambiguity, a
890 name will be interpreted as an input\-column name rather than an output column name\&.
897 are present as grouping elements, then the
899 clause as a whole defines some number of independent
900 \fIgrouping sets\fR\&. The effect of this is equivalent to constructing a
902 between subqueries with the individual grouping sets as their
904 clauses\&. The optional
906 clause removes duplicate sets before processing; it does
911 UNION DISTINCT\&. For further details on the handling of grouping sets see
914 Aggregate functions, if any are used, are computed across all rows making up each group, producing a separate value for each group\&. (If there are aggregate functions but no
916 clause, the query is treated as having a single group comprising all the selected rows\&.) The set of rows fed to each aggregate function can be further filtered by attaching a
918 clause to the aggregate function call; see
920 for more information\&. When a
922 clause is present, only those rows matching it are included in the input to that aggregate function\&.
926 is present, or any aggregate functions are present, it is not valid for the
928 list expressions to refer to ungrouped columns except within aggregate functions or when the ungrouped column is functionally dependent on the grouped columns, since there would otherwise be more than one possible value to return for an ungrouped column\&. A functional dependency exists if the grouped columns (or a subset thereof) are the primary key of the table containing the ungrouped column\&.
930 Keep in mind that all aggregate functions are evaluated before evaluating any
936 list\&. This means that, for example, a
938 expression cannot be used to skip evaluation of an aggregate function; see
947 cannot be specified with
953 clause has the general form
959 HAVING \fIcondition\fR
967 is the same as specified for the
972 eliminates group rows that do not satisfy the condition\&.
977 filters individual rows before the application of
980 filters group rows created by
981 GROUP BY\&. Each column referenced in
983 must unambiguously reference a grouping column, unless the reference appears within an aggregate function or the ungrouped column is functionally dependent on the grouping columns\&.
987 turns a query into a grouped query even if there is no
989 clause\&. This is the same as what happens when the query contains aggregate functions but no
991 clause\&. All the selected rows are considered to form a single group, and the
995 clause can only reference table columns from within aggregate functions\&. Such a query will emit a single row if the
997 condition is true, zero rows if it is not true\&.
1005 cannot be specified with
1011 clause has the general form
1017 WINDOW \fIwindow_name\fR AS ( \fIwindow_definition\fR ) [, \&.\&.\&.]
1025 is a name that can be referenced from
1027 clauses or subsequent window definitions, and
1028 \fIwindow_definition\fR
1035 [ \fIexisting_window_name\fR ]
1036 [ PARTITION BY \fIexpression\fR [, \&.\&.\&.] ]
1037 [ ORDER BY \fIexpression\fR [ ASC | DESC | USING \fIoperator\fR ] [ NULLS { FIRST | LAST } ] [, \&.\&.\&.] ]
1038 [ \fIframe_clause\fR ]
1045 \fIexisting_window_name\fR
1046 is specified it must refer to an earlier entry in the
1048 list; the new window copies its partitioning clause from that entry, as well as its ordering clause if any\&. In this case the new window cannot specify its own
1050 clause, and it can specify
1052 only if the copied window does not have one\&. The new window always uses its own frame clause; the copied window must not specify a frame clause\&.
1056 list are interpreted in much the same fashion as elements of a
1058 clause, except that they are always simple expressions and never the name or number of an output column\&. Another difference is that these expressions can contain aggregate function calls, which are not allowed in a regular
1060 clause\&. They are allowed here because windowing occurs after grouping and aggregation\&.
1062 Similarly, the elements of the
1064 list are interpreted in much the same fashion as elements of a statement\-level
1066 clause, except that the expressions are always taken as simple expressions and never the name or number of an output column\&.
1072 for window functions that depend on the frame (not all do)\&. The window frame is a set of related rows for each row of the query (called the
1081 { RANGE | ROWS | GROUPS } \fIframe_start\fR [ \fIframe_exclusion\fR ]
1082 { RANGE | ROWS | GROUPS } BETWEEN \fIframe_start\fR AND \fIframe_end\fR [ \fIframe_exclusion\fR ]
1099 \fIoffset\fR PRECEDING
1101 \fIoffset\fR FOLLOWING
1109 \fIframe_exclusion\fR
1127 is omitted it defaults to
1128 CURRENT ROW\&. Restrictions are that
1131 UNBOUNDED FOLLOWING,
1134 UNBOUNDED PRECEDING, and the
1136 choice cannot appear earlier in the above list of
1142 choice does \(em for example
1143 RANGE BETWEEN CURRENT ROW AND \fIoffset\fR PRECEDING
1146 The default framing option is
1147 RANGE UNBOUNDED PRECEDING, which is the same as
1148 RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW; it sets the frame to be all rows from the partition start up through the current row\*(Aqs last
1150 (a row that the window\*(Aqs
1152 clause considers equivalent to the current row; all rows are peers if there is no
1153 ORDER BY)\&. In general,
1155 means that the frame starts with the first row of the partition, and similarly
1157 means that the frame ends with the last row of the partition, regardless of
1166 means that the frame starts or ends with the current row; but in
1170 mode it means that the frame starts or ends with the current row\*(Aqs first or last peer in the
1178 options vary in meaning depending on the frame mode\&. In
1182 is an integer indicating that the frame starts or ends that many rows before or after the current row\&. In
1186 is an integer indicating that the frame starts or ends that many peer groups before or after the current row\*(Aqs peer group, where a
1188 is a group of rows that are equivalent according to the window\*(Aqs
1194 option requires that there be exactly one
1196 column in the window definition\&. Then the frame contains those rows whose ordering column value is no more than
1199 PRECEDING) or more than (for
1200 FOLLOWING) the current row\*(Aqs ordering column value\&. In these cases the data type of the
1202 expression depends on the data type of the ordering column\&. For numeric ordering columns it is typically of the same type as the ordering column, but for datetime ordering columns it is an
1203 interval\&. In all these cases, the value of the
1205 must be non\-null and non\-negative\&. Also, while the
1207 does not have to be a simple constant, it cannot contain variables, aggregate functions, or window functions\&.
1210 \fIframe_exclusion\fR
1211 option allows rows around the current row to be excluded from the frame, even if they would be included according to the frame start and frame end options\&.
1213 excludes the current row from the frame\&.
1215 excludes the current row and its ordering peers from the frame\&.
1217 excludes any peers of the current row from the frame, but not the current row itself\&.
1219 simply specifies explicitly the default behavior of not excluding the current row or its peers\&.
1223 mode can produce unpredictable results if the
1225 ordering does not order the rows uniquely\&. The
1229 modes are designed to ensure that rows that are peers in the
1231 ordering are treated alike: all rows of a given peer group will be in the frame or excluded from it\&.
1235 clause is to specify the behavior of
1237 appearing in the query\*(Aqs
1241 clause\&. These functions can reference the
1243 clause entries by name in their
1247 clause entry does not have to be referenced anywhere, however; if it is not used in the query it is simply ignored\&. It is possible to use window functions without any
1249 clause at all, since a window function call can specify its window definition directly in its
1251 clause\&. However, the
1253 clause saves typing when the same window definition is needed for more than one window function\&.
1261 cannot be specified with
1264 Window functions are described in detail in
1266 Section\ \&4.2.8, and
1272 list (between the key words
1275 FROM) specifies expressions that form the output rows of the
1277 statement\&. The expressions can (and usually do) refer to columns computed in the
1281 Just as in a table, every output column of a
1283 has a name\&. In a simple
1285 this name is just used to label the column for display, but when the
1287 is a sub\-query of a larger query, the name is seen by the larger query as the column name of the virtual table produced by the sub\-query\&. To specify the name to use for an output column, write
1290 after the column\*(Aqs expression\&. (You can omit
1291 AS, but only if the desired output name does not match any
1294 Appendix\ \&C)\&. For protection against possible future keyword additions, it is recommended that you always either write
1296 or double\-quote the output name\&.) If you do not specify a column name, a name is chosen automatically by
1297 PostgreSQL\&. If the column\*(Aqs expression is a simple column reference then the chosen name is the same as that column\*(Aqs name\&. In more complex cases a function or type name may be used, or the system may fall back on a generated name such as
1300 An output column\*(Aqs name can be used to refer to the column\*(Aqs value in
1304 clauses, but not in the
1308 clauses; there you must write out the expression instead\&.
1310 Instead of an expression,
1312 can be written in the output list as a shorthand for all the columns of the selected rows\&. Also, you can write
1313 \fItable_name\fR\&.*
1314 as a shorthand for the columns coming from just that table\&. In these cases it is not possible to specify new names with
1315 AS; the output column names will be the same as the table columns\*(Aq names\&.
1317 According to the SQL standard, the expressions in the output list should be computed before applying
1320 LIMIT\&. This is obviously necessary when using
1321 DISTINCT, since otherwise it\*(Aqs not clear what values are being made distinct\&. However, in many cases it is convenient if output expressions are computed after
1324 LIMIT; particularly if the output list contains any volatile or expensive functions\&. With that behavior, the order of function evaluations is more intuitive and there will not be evaluations corresponding to rows that never appear in the output\&.
1326 will effectively evaluate output expressions after sorting and limiting, so long as those expressions are not referenced in
1330 GROUP BY\&. (As a counterexample,
1331 SELECT f(x) FROM tab ORDER BY 1
1332 clearly must evaluate
1334 before sorting\&.) Output expressions that contain set\-returning functions are effectively evaluated after sorting and before limiting, so that
1336 will act to cut off the output from a set\-returning function\&.
1342 .nr an-no-space-flag 1
1351 versions before 9\&.6 did not provide any guarantees about the timing of evaluation of output expressions versus sorting and limiting; it depended on the form of the chosen query plan\&.
1354 .SS "DISTINCT Clause"
1358 is specified, all duplicate rows are removed from the result set (one row is kept from each group of duplicates)\&.
1360 specifies the opposite: all rows are kept; that is the default\&.
1362 SELECT DISTINCT ON ( \fIexpression\fR [, \&.\&.\&.] )
1363 keeps only the first row of each set of rows where the given expressions evaluate to equal\&. The
1365 expressions are interpreted using the same rules as for
1367 (see above)\&. Note that the
1369 of each set is unpredictable unless
1371 is used to ensure that the desired row appears first\&. For example:
1377 SELECT DISTINCT ON (location) location, time, report
1378 FROM weather_reports
1379 ORDER BY location, time DESC;
1385 retrieves the most recent weather report for each location\&. But if we had not used
1387 to force descending order of time values for each location, we\*(Aqd have gotten a report from an unpredictable time for each location\&.
1391 expression(s) must match the leftmost
1393 expression(s)\&. The
1395 clause will normally contain additional expression(s) that determine the desired precedence of rows within each
1405 cannot be specified with
1411 clause has this general form:
1417 \fIselect_statement\fR UNION [ ALL | DISTINCT ] \fIselect_statement\fR
1423 \fIselect_statement\fR
1426 statement without an
1436 can be attached to a subexpression if it is enclosed in parentheses\&. Without parentheses, these clauses will be taken to apply to the result of the
1437 UNION, not to its right\-hand input expression\&.)
1441 operator computes the set union of the rows returned by the involved
1443 statements\&. A row is in the set union of two result sets if it appears in at least one of the result sets\&. The two
1445 statements that represent the direct operands of the
1447 must produce the same number of columns, and corresponding columns must be of compatible data types\&.
1451 does not contain any duplicate rows unless the
1453 option is specified\&.
1455 prevents elimination of duplicates\&. (Therefore,
1457 is usually significantly quicker than
1462 can be written to explicitly specify the default behavior of eliminating duplicate rows\&.
1466 operators in the same
1468 statement are evaluated left to right, unless otherwise indicated by parentheses\&.
1476 cannot be specified either for a
1478 result or for any input of a
1480 .SS "INTERSECT Clause"
1484 clause has this general form:
1490 \fIselect_statement\fR INTERSECT [ ALL | DISTINCT ] \fIselect_statement\fR
1496 \fIselect_statement\fR
1499 statement without an
1510 operator computes the set intersection of the rows returned by the involved
1512 statements\&. A row is in the intersection of two result sets if it appears in both result sets\&.
1516 does not contain any duplicate rows unless the
1518 option is specified\&. With
1521 duplicates in the left table and
1523 duplicates in the right table will appear min(\fIm\fR,\fIn\fR) times in the result set\&.
1525 can be written to explicitly specify the default behavior of eliminating duplicate rows\&.
1529 operators in the same
1531 statement are evaluated left to right, unless parentheses dictate otherwise\&.
1533 binds more tightly than
1535 A UNION B INTERSECT C
1537 A UNION (B INTERSECT C)\&.
1545 cannot be specified either for an
1547 result or for any input of an
1553 clause has this general form:
1559 \fIselect_statement\fR EXCEPT [ ALL | DISTINCT ] \fIselect_statement\fR
1565 \fIselect_statement\fR
1568 statement without an
1579 operator computes the set of rows that are in the result of the left
1581 statement but not in the result of the right one\&.
1585 does not contain any duplicate rows unless the
1587 option is specified\&. With
1590 duplicates in the left table and
1592 duplicates in the right table will appear max(\fIm\fR\-\fIn\fR,0) times in the result set\&.
1594 can be written to explicitly specify the default behavior of eliminating duplicate rows\&.
1598 operators in the same
1600 statement are evaluated left to right, unless parentheses dictate otherwise\&.
1602 binds at the same level as
1611 cannot be specified either for an
1613 result or for any input of an
1615 .SS "ORDER BY Clause"
1619 clause has this general form:
1625 ORDER BY \fIexpression\fR [ ASC | DESC | USING \fIoperator\fR ] [ NULLS { FIRST | LAST } ] [, \&.\&.\&.]
1633 clause causes the result rows to be sorted according to the specified expression(s)\&. If two rows are equal according to the leftmost expression, they are compared according to the next expression and so on\&. If they are equal according to all specified expressions, they are returned in an implementation\-dependent order\&.
1637 can be the name or ordinal number of an output column (\fBSELECT\fR
1638 list item), or it can be an arbitrary expression formed from input\-column values\&.
1640 The ordinal number refers to the ordinal (left\-to\-right) position of the output column\&. This feature makes it possible to define an ordering on the basis of a column that does not have a unique name\&. This is never absolutely necessary because it is always possible to assign a name to an output column using the
1644 It is also possible to use arbitrary expressions in the
1646 clause, including columns that do not appear in the
1648 output list\&. Thus the following statement is valid:
1654 SELECT name FROM distributors ORDER BY code;
1660 A limitation of this feature is that an
1662 clause applying to the result of a
1666 clause can only specify an output column name or number, not an expression\&.
1670 expression is a simple name that matches both an output column name and an input column name,
1672 will interpret it as the output column name\&. This is the opposite of the choice that
1674 will make in the same situation\&. This inconsistency is made to be compatible with the SQL standard\&.
1676 Optionally one can add the key word
1680 (descending) after any expression in the
1682 clause\&. If not specified,
1684 is assumed by default\&. Alternatively, a specific ordering operator name can be specified in the
1686 clause\&. An ordering operator must be a less\-than or greater\-than member of some B\-tree operator family\&.
1688 is usually equivalent to
1692 is usually equivalent to
1693 USING >\&. (But the creator of a user\-defined data type can define exactly what the default sort ordering is, and it might correspond to operators with other names\&.)
1697 is specified, null values sort after all non\-null values; if
1699 is specified, null values sort before all non\-null values\&. If neither is specified, the default behavior is
1703 is specified or implied, and
1707 is specified (thus, the default is to act as though nulls are larger than non\-nulls)\&. When
1709 is specified, the default nulls ordering depends on whether the operator is a less\-than or greater\-than operator\&.
1711 Note that ordering options apply only to the expression they follow; for example
1713 does not mean the same thing as
1714 ORDER BY x DESC, y DESC\&.
1716 Character\-string data is sorted according to the collation that applies to the column being sorted\&. That can be overridden at need by including a
1719 \fIexpression\fR, for example
1720 ORDER BY mycolumn COLLATE "en_US"\&. For more information see
1728 clause consists of two independent sub\-clauses:
1734 LIMIT { \fIcount\fR | ALL }
1743 specifies the maximum number of rows to return, while
1745 specifies the number of rows to skip before starting to return rows\&. When both are specified,
1747 rows are skipped before starting to count the
1749 rows to be returned\&.
1753 expression evaluates to NULL, it is treated as
1754 LIMIT ALL, i\&.e\&., no limit\&. If
1756 evaluates to NULL, it is treated the same as
1759 SQL:2008 introduced a different syntax to achieve the same result, which
1761 also supports\&. It is:
1767 OFFSET \fIstart\fR { ROW | ROWS }
1768 FETCH { FIRST | NEXT } [ \fIcount\fR ] { ROW | ROWS } { ONLY | WITH TIES }
1778 value is required by the standard to be a literal constant, a parameter, or a variable name; as a
1780 extension, other expressions are allowed, but will generally need to be enclosed in parentheses to avoid ambiguity\&. If
1784 clause, it defaults to 1\&. The
1786 option is used to return any additional rows that tie for the last place in the result set according to the
1790 is mandatory in this case, and
1800 are noise words that don\*(Aqt influence the effects of these clauses\&. According to the standard, the
1802 clause must come before the
1804 clause if both are present; but
1806 is laxer and allows either order\&.
1809 LIMIT, it is a good idea to use an
1811 clause that constrains the result rows into a unique order\&. Otherwise you will get an unpredictable subset of the query\*(Aqs rows \(em you might be asking for the tenth through twentieth rows, but tenth through twentieth in what ordering? You don\*(Aqt know what ordering unless you specify
1814 The query planner takes
1816 into account when generating a query plan, so you are very likely to get different plans (yielding different row orders) depending on what you use for
1819 OFFSET\&. Thus, using different
1821 values to select different subsets of a query result
1822 \fIwill give inconsistent results\fR
1823 unless you enforce a predictable result ordering with
1824 ORDER BY\&. This is not a bug; it is an inherent consequence of the fact that SQL does not promise to deliver the results of a query in any particular order unless
1826 is used to constrain the order\&.
1828 It is even possible for repeated executions of the same
1830 query to return different subsets of the rows of a table, if there is not an
1832 to enforce selection of a deterministic subset\&. Again, this is not a bug; determinism of the results is simply not guaranteed in such a case\&.
1833 .SS "The Locking Clause"
1841 locking clauses; they affect how
1843 locks rows as they are obtained from the table\&.
1845 The locking clause has the general form
1851 FOR \fIlock_strength\fR [ OF \fIfrom_reference\fR [, \&.\&.\&.] ] [ NOWAIT | SKIP LOCKED ]
1874 \fIfrom_reference\fR
1881 clause\&. For more information on each row\-level lock mode, refer to
1882 Section\ \&13.3.2\&.
1884 To prevent the operation from waiting for other transactions to commit, use either the
1889 NOWAIT, the statement reports an error, rather than waiting, if a selected row cannot be locked immediately\&. With
1890 SKIP LOCKED, any selected rows that cannot be immediately locked are skipped\&. Skipping locked rows provides an inconsistent view of the data, so this is not suitable for general purpose work, but can be used to avoid lock contention with multiple consumers accessing a queue\-like table\&. Note that
1894 apply only to the row\-level lock(s) \(em the required
1896 table\-level lock is still taken in the ordinary way (see
1897 Chapter\ \&13)\&. You can use
1901 option first, if you need to acquire the table\-level lock without waiting\&.
1903 If specific tables are named in a locking clause, then only rows coming from those tables are locked; any other tables used in the
1905 are simply read as usual\&. A locking clause without a table list affects all tables used in the statement\&. If a locking clause is applied to a view or sub\-query, it affects all tables used in the view or sub\-query\&. However, these clauses do not apply to
1907 queries referenced by the primary query\&. If you want row locking to occur within a
1909 query, specify a locking clause within the
1913 Multiple locking clauses can be written if it is necessary to specify different locking behavior for different tables\&. If the same table is mentioned (or implicitly affected) by more than one locking clause, then it is processed as if it was only specified by the strongest one\&. Similarly, a table is processed as
1915 if that is specified in any of the clauses affecting it\&. Otherwise, it is processed as
1917 if that is specified in any of the clauses affecting it\&.
1919 The locking clauses cannot be used in contexts where returned rows cannot be clearly identified with individual table rows; for example they cannot be used with aggregation\&.
1921 When a locking clause appears at the top level of a
1923 query, the rows that are locked are exactly those that are returned by the query; in the case of a join query, the rows locked are those that contribute to returned join rows\&. In addition, rows that satisfied the query conditions as of the query snapshot will be locked, although they will not be returned if they were updated after the snapshot and no longer satisfy the query conditions\&. If a
1925 is used, locking stops once enough rows have been returned to satisfy the limit (but note that rows skipped over by
1927 will get locked)\&. Similarly, if a locking clause is used in a cursor\*(Aqs query, only rows actually fetched or stepped past by the cursor will be locked\&.
1929 When a locking clause appears in a sub\-\fBSELECT\fR, the rows locked are those returned to the outer query by the sub\-query\&. This might involve fewer rows than inspection of the sub\-query alone would suggest, since conditions from the outer query might be used to optimize execution of the sub\-query\&. For example,
1935 SELECT * FROM (SELECT * FROM mytable FOR UPDATE) ss WHERE col1 = 5;
1941 will lock only rows having
1942 col1 = 5, even though that condition is not textually within the sub\-query\&.
1944 Previous releases failed to preserve a lock which is upgraded by a later savepoint\&. For example, this code:
1951 SELECT * FROM mytable WHERE key = 1 FOR UPDATE;
1953 UPDATE mytable SET \&.\&.\&. WHERE key = 1;
1960 would fail to preserve the
1963 \fBROLLBACK TO\fR\&. This has been fixed in release 9\&.3\&.
1969 .nr an-no-space-flag 1
1977 It is possible for a
1979 command running at the
1981 transaction isolation level and using
1983 and a locking clause to return rows out of order\&. This is because
1985 is applied first\&. The command sorts the result, but might then block trying to obtain a lock on one or more of the rows\&. Once the
1987 unblocks, some of the ordering column values might have been modified, leading to those rows appearing to be out of order (though they are in order in terms of the original column values)\&. This can be worked around at need by placing the
1989 clause in a sub\-query, for example
1995 SELECT * FROM (SELECT * FROM mytable FOR UPDATE) ss ORDER BY column1;
2001 Note that this will result in locking all rows of
2004 at the top level would lock only the actually returned rows\&. This can make for a significant performance difference, particularly if the
2008 or other restrictions\&. So this technique is recommended only if concurrent updates of the ordering columns are expected and a strictly sorted result is required\&.
2014 transaction isolation level this would cause a serialization failure (with an
2017 \*(Aq40001\*(Aq), so there is no possibility of receiving rows out of order under these isolation levels\&.
2040 SELECT * FROM \fIname\fR
2046 It can be used as a top\-level command or as a space\-saving syntax variant in parts of complex queries\&. Only the
2057 locking clauses can be used with
2060 clause and any form of aggregation cannot be used\&.
2072 SELECT f\&.title, f\&.did, d\&.name, f\&.date_prod, f\&.kind
2073 FROM distributors d JOIN films f USING (did);
2075 title | did | name | date_prod | kind
2076 \-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-
2077 The Third Man | 101 | British Lion | 1949\-12\-23 | Drama
2078 The African Queen | 101 | British Lion | 1951\-08\-11 | Romantic
2087 of all films and group the results by
2094 SELECT kind, sum(len) AS total FROM films GROUP BY kind;
2097 \-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-
2110 of all films, group the results by
2112 and show those group totals that are less than 5 hours:
2118 SELECT kind, sum(len) AS total
2121 HAVING sum(len) < interval \*(Aq5 hours\*(Aq;
2124 \-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-
2132 The following two examples are identical ways of sorting the individual results according to the contents of the second column (name):
2138 SELECT * FROM distributors ORDER BY name;
2139 SELECT * FROM distributors ORDER BY 2;
2142 \-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
2143 109 | 20th Century Fox
2144 110 | Bavaria Atelier
2147 102 | Jean Luc Godard
2152 105 | United Artists
2154 112 | Warner Bros\&.
2161 The next example shows how to obtain the union of the tables
2164 actors, restricting the results to those that begin with the letter W in each table\&. Only distinct rows are wanted, so the key word
2172 distributors: actors:
2173 did | name id | name
2174 \-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\- \-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
2175 108 | Westward 1 | Woody Allen
2176 111 | Walt Disney 2 | Warren Beatty
2177 112 | Warner Bros\&. 3 | Walter Matthau
2180 SELECT distributors\&.name
2182 WHERE distributors\&.name LIKE \*(AqW%\*(Aq
2184 SELECT actors\&.name
2186 WHERE actors\&.name LIKE \*(AqW%\*(Aq;
2189 \-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
2201 This example shows how to use a function in the
2203 clause, both with and without a column definition list:
2209 CREATE FUNCTION distributors(int) RETURNS SETOF distributors AS $$
2210 SELECT * FROM distributors WHERE did = $1;
2213 SELECT * FROM distributors(111);
2215 \-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-
2218 CREATE FUNCTION distributors_2(int) RETURNS SETOF record AS $$
2219 SELECT * FROM distributors WHERE did = $1;
2222 SELECT * FROM distributors_2(111) AS (f1 int, f2 text);
2224 \-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-
2231 Here is an example of a function with an ordinality column added:
2237 SELECT * FROM unnest(ARRAY[\*(Aqa\*(Aq,\*(Aqb\*(Aq,\*(Aqc\*(Aq,\*(Aqd\*(Aq,\*(Aqe\*(Aq,\*(Aqf\*(Aq]) WITH ORDINALITY;
2239 \-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-
2252 This example shows how to use a simple
2261 SELECT random() as x FROM generate_series(1, 3)
2267 \-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
2270 0\&.0735620250925422
2273 0\&.0735620250925422
2281 query was evaluated only once, so that we got two sets of the same three random values\&.
2285 to find all subordinates (direct or indirect) of the employee Mary, and their level of indirectness, from a table that shows only direct subordinates:
2291 WITH RECURSIVE employee_recursive(distance, employee_name, manager_name) AS (
2292 SELECT 1, employee_name, manager_name
2294 WHERE manager_name = \*(AqMary\*(Aq
2296 SELECT er\&.distance + 1, e\&.employee_name, e\&.manager_name
2297 FROM employee_recursive er, employee e
2298 WHERE er\&.employee_name = e\&.manager_name
2300 SELECT distance, employee_name FROM employee_recursive;
2306 Notice the typical form of recursive queries: an initial condition, followed by
2307 UNION, followed by the recursive part of the query\&. Be sure that the recursive part of the query will eventually return no tuples, or else the query will loop indefinitely\&. (See
2309 for more examples\&.)
2313 to apply a set\-returning function
2314 \fBget_product_names()\fR
2323 SELECT m\&.name AS mname, pname
2324 FROM manufacturers m, LATERAL get_product_names(m\&.id) pname;
2330 Manufacturers not currently having any products would not appear in the result, since it is an inner join\&. If we wished to include the names of such manufacturers in the result, we could do:
2336 SELECT m\&.name AS mname, pname
2337 FROM manufacturers m LEFT JOIN LATERAL get_product_names(m\&.id) pname ON true;
2346 statement is compatible with the SQL standard\&. But there are some extensions and some missing features\&.
2347 .SS "Omitted FROM Clauses"
2350 allows one to omit the
2352 clause\&. It has a straightforward use to compute the results of simple expressions:
2361 \-\-\-\-\-\-\-\-\-\-
2370 databases cannot do this except by introducing a dummy one\-row table from which to do the
2372 .SS "Empty SELECT Lists"
2374 The list of output expressions after
2376 can be empty, producing a zero\-column result table\&. This is not valid syntax according to the SQL standard\&.
2378 allows it to be consistent with allowing zero\-column tables\&. However, an empty list is not allowed when
2381 .SS "Omitting the AS Key Word"
2383 In the SQL standard, the optional key word
2385 can be omitted before an output column name whenever the new column name is a valid column name (that is, not the same as any reserved keyword)\&.
2387 is slightly more restrictive:
2389 is required if the new column name matches any keyword at all, reserved or not\&. Recommended practice is to use
2391 or double\-quote output column names, to prevent any possible conflict against future keyword additions\&.
2395 items, both the standard and
2399 to be omitted before an alias that is an unreserved keyword\&. But this is impractical for output column names, because of syntactic ambiguities\&.
2400 .SS "Omitting Sub\-SELECT Aliases in FROM"
2402 According to the SQL standard, a sub\-\fBSELECT\fR
2405 list must have an alias\&. In
2406 PostgreSQL, this alias may be omitted\&.
2407 .SS "ONLY and Inheritance"
2409 The SQL standard requires parentheses around the table name when writing
2411 SELECT * FROM ONLY (tab1), ONLY (tab2) WHERE \&.\&.\&.\&.
2413 considers these parentheses to be optional\&.
2418 to be written to explicitly specify the non\-ONLY
2419 behavior of including child tables\&. The standard does not allow this\&.
2421 (These points apply equally to all SQL commands supporting the
2424 .SS "TABLESAMPLE Clause Restrictions"
2428 clause is currently accepted only on regular tables and materialized views\&. According to the SQL standard it should be possible to apply it to any
2431 .SS "Function Calls in FROM"
2434 allows a function call to be written directly as a member of the
2436 list\&. In the SQL standard it would be necessary to wrap such a function call in a sub\-\fBSELECT\fR; that is, the syntax
2437 FROM \fIfunc\fR(\&.\&.\&.) \fIalias\fR
2438 is approximately equivalent to
2439 FROM LATERAL (SELECT \fIfunc\fR(\&.\&.\&.)) \fIalias\fR\&. Note that
2441 is considered to be implicit; this is because the standard requires
2450 the same as other set\-returning functions\&.
2451 .SS "Namespace Available to GROUP BY and ORDER BY"
2453 In the SQL\-92 standard, an
2455 clause can only use output column names or numbers, while a
2457 clause can only use expressions based on input column names\&.
2459 extends each of these clauses to allow the other choice as well (but it uses the standard\*(Aqs interpretation if there is ambiguity)\&.
2461 also allows both clauses to specify arbitrary expressions\&. Note that names appearing in an expression will always be taken as input\-column names, not as output\-column names\&.
2463 SQL:1999 and later use a slightly different definition which is not entirely upward compatible with SQL\-92\&. In most cases, however,
2469 expression the same way SQL:1999 does\&.
2470 .SS "Functional Dependencies"
2473 recognizes functional dependency (allowing columns to be omitted from
2474 GROUP BY) only when a table\*(Aqs primary key is included in the
2476 list\&. The SQL standard specifies additional conditions that should be recognized\&.
2477 .SS "LIMIT and OFFSET"
2484 PostgreSQL\-specific syntax, also used by
2485 MySQL\&. The SQL:2008 standard has introduced the clauses
2486 OFFSET \&.\&.\&. FETCH {FIRST|NEXT} \&.\&.\&.
2487 for the same functionality, as shown above in
2488 LIMIT Clause\&. This syntax is also used by
2489 IBM DB2\&. (Applications written for
2491 frequently use a workaround involving the automatically generated
2493 column, which is not available in PostgreSQL, to implement the effects of these clauses\&.)
2494 .SS "FOR NO KEY UPDATE, FOR UPDATE, FOR SHARE, FOR KEY SHARE"
2498 appears in the SQL standard, the standard allows it only as an option of
2499 \fBDECLARE CURSOR\fR\&.
2503 query as well as in sub\-\fBSELECT\fRs, but this is an extension\&. The
2508 variants, as well as the
2512 options, do not appear in the standard\&.
2513 .SS "Data\-Modifying Statements in WITH"
2523 queries\&. This is not found in the SQL standard\&.
2524 .SS "Nonstandard Clauses"
2526 DISTINCT ON ( \&.\&.\&. )
2527 is an extension of the SQL standard\&.
2529 ROWS FROM( \&.\&.\&. )
2530 is an extension of the SQL standard\&.
2538 are extensions of the SQL standard\&.