SELECT
SELECT, TABLE, WITH — retrieve rows from a table or view
Synopsis
[ WITH [ RECURSIVE ]with_query
[, ...] ]SELECT [ ALL | DISTINCT [ ON (expression
[, ...] ) ] ] [ { * |expression
[ [ AS ]output_name
] } [, ...] ] [ FROMfrom_item
[, ...] ] [ WHEREcondition
] [ GROUP BY [ ALL | DISTINCT ]grouping_element
[, ...] ] [ HAVINGcondition
] [ WINDOWwindow_name
AS (window_definition
) [, ...] ] [ { UNION | INTERSECT | EXCEPT } [ ALL | DISTINCT ]select
] [ ORDER BYexpression
[ ASC | DESC | USINGoperator
] [ NULLS { FIRST | LAST } ] [, ...] ] [ LIMIT {count
| ALL } ] [ OFFSETstart
[ ROW | ROWS ] ] [ FETCH { FIRST | NEXT } [count
] { ROW | ROWS } { ONLY | WITH TIES } ] [ FOR { UPDATE | NO KEY UPDATE | SHARE | KEY SHARE } [ OFfrom_reference
[, ...] ] [ NOWAIT | SKIP LOCKED ] [...] ]wherefrom_item
can be one of: [ ONLY ]table_name
[ * ] [ [ AS ]alias
[ (column_alias
[, ...] ) ] ] [ TABLESAMPLEsampling_method
(argument
[, ...] ) [ REPEATABLE (seed
) ] ] [ LATERAL ] (select
) [ [ AS ]alias
[ (column_alias
[, ...] ) ] ]with_query_name
[ [ AS ]alias
[ (column_alias
[, ...] ) ] ] [ LATERAL ]function_name
( [argument
[, ...] ] ) [ WITH ORDINALITY ] [ [ AS ]alias
[ (column_alias
[, ...] ) ] ] [ LATERAL ]function_name
( [argument
[, ...] ] ) [ AS ]alias
(column_definition
[, ...] ) [ LATERAL ]function_name
( [argument
[, ...] ] ) AS (column_definition
[, ...] ) [ LATERAL ] ROWS FROM(function_name
( [argument
[, ...] ] ) [ AS (column_definition
[, ...] ) ] [, ...] ) [ WITH ORDINALITY ] [ [ AS ]alias
[ (column_alias
[, ...] ) ] ]from_item
join_type
from_item
{ ONjoin_condition
| USING (join_column
[, ...] ) [ ASjoin_using_alias
] }from_item
NATURALjoin_type
from_item
from_item
CROSS JOINfrom_item
andgrouping_element
can be one of: ( )expression
(expression
[, ...] ) ROLLUP ( {expression
| (expression
[, ...] ) } [, ...] ) CUBE ( {expression
| (expression
[, ...] ) } [, ...] ) GROUPING SETS (grouping_element
[, ...] )andwith_query
is:with_query_name
[ (column_name
[, ...] ) ] AS [ [ NOT ] MATERIALIZED ] (select
|values
|insert
|update
|delete
|merge
) [ SEARCH { BREADTH | DEPTH } FIRST BYcolumn_name
[, ...] SETsearch_seq_col_name
] [ CYCLEcolumn_name
[, ...] SETcycle_mark_col_name
[ TOcycle_mark_value
DEFAULTcycle_mark_default
] USINGcycle_path_col_name
]TABLE [ ONLY ]table_name
[ * ]
Description
SELECT
retrieves rows from zero or more tables. The general processing ofSELECT
is as follows:
All queries in the
WITH
list are computed. These effectively serve as temporary tables that can be referenced in theFROM
list. AWITH
query that is referenced more than once inFROM
is computed only once, unless specified otherwise withNOT MATERIALIZED
. (SeeWITH Clause below.)All elements in the
FROM
list are computed. (Each element in theFROM
list is a real or virtual table.) If more than one element is specified in theFROM
list, they are cross-joined together. (SeeFROM Clause below.)If the
WHERE
clause is specified, all rows that do not satisfy the condition are eliminated from the output. (SeeWHERE Clause below.)If the
GROUP BY
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 theHAVING
clause is present, it eliminates groups that do not satisfy the given condition. (SeeGROUP BY Clause andHAVING Clause below.) Although query output columns are nominally computed in the next step, they can also be referenced (by name or ordinal number) in theGROUP BY
clause.The actual output rows are computed using the
SELECT
output expressions for each selected row or row group. (SeeSELECT List below.)SELECT DISTINCT
eliminates duplicate rows from the result.SELECT DISTINCT ON
eliminates rows that match on all the specified expressions.SELECT ALL
(the default) will return all candidate rows, including duplicates. (SeeDISTINCT Clause below.)Using the operators
UNION
,INTERSECT
, andEXCEPT
, the output of more than oneSELECT
statement can be combined to form a single result set. TheUNION
operator returns all rows that are in one or both of the result sets. TheINTERSECT
operator returns all rows that are strictly in both result sets. TheEXCEPT
operator returns the rows that are in the first result set but not in the second. In all three cases, duplicate rows are eliminated unlessALL
is specified. The noise wordDISTINCT
can be added to explicitly specify eliminating duplicate rows. Notice thatDISTINCT
is the default behavior here, even thoughALL
is the default forSELECT
itself. (SeeUNION Clause,INTERSECT Clause, andEXCEPT Clause below.)If the
ORDER BY
clause is specified, the returned rows are sorted in the specified order. IfORDER BY
is not given, the rows are returned in whatever order the system finds fastest to produce. (SeeORDER BY Clause below.)If the
LIMIT
(orFETCH FIRST
) orOFFSET
clause is specified, theSELECT
statement only returns a subset of the result rows. (SeeLIMIT Clause below.)If
FOR UPDATE
,FOR NO KEY UPDATE
,FOR SHARE
orFOR KEY SHARE
is specified, theSELECT
statement locks the selected rows against concurrent updates. (SeeThe Locking Clause below.)
You must haveSELECT
privilege on each column used in aSELECT
command. The use ofFOR NO KEY UPDATE
,FOR UPDATE
,FOR SHARE
orFOR KEY SHARE
requiresUPDATE
privilege as well (for at least one column of each table so selected).
Parameters
WITH
Clause#
TheWITH
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 aSELECT
,TABLE
,VALUES
,INSERT
,UPDATE
,DELETE
, orMERGE
statement. When writing a data-modifying statement (INSERT
,UPDATE
,DELETE
, orMERGE
) inWITH
, it is usual to include aRETURNING
clause. It is the output ofRETURNING
,not the underlying table that the statement modifies, that forms the temporary table that is read by the primary query. IfRETURNING
is omitted, the statement is still executed, but it produces no output so it cannot be referenced as a table by the primary query.
A name (without schema qualification) must be specified for eachWITH
query. Optionally, a list of column names can be specified; if this is omitted, the column names are inferred from the subquery.
IfRECURSIVE
is specified, it allows aSELECT
subquery to reference itself by name. Such a subquery must have the form
non_recursive_term
UNION [ ALL | DISTINCT ]recursive_term
where the recursive self-reference must appear on the right-hand side of theUNION
. Only one recursive self-reference is permitted per query. Recursive data-modifying statements are not supported, but you can use the results of a recursiveSELECT
query in a data-modifying statement. SeeSection 7.8 for an example.
Another effect ofRECURSIVE
is thatWITH
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.) WithoutRECURSIVE
,WITH
queries can only reference siblingWITH
queries that are earlier in theWITH
list.
When there are multiple queries in theWITH
clause,RECURSIVE
should be written only once, immediately afterWITH
. It applies to all queries in theWITH
clause, though it has no effect on queries that do not use recursion or forward references.
The optionalSEARCH
clause computes asearch sequence column 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 namedsearch_seq_col_name
will be added to the result column list of theWITH
query. This column can be ordered by in the outer query to achieve the respective ordering. SeeSection 7.8.2.1 for examples.
The optionalCYCLE
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 namedcycle_mark_col_name
will be added to the result column list of theWITH
query. This column will be set tocycle_mark_value
when a cycle has been detected, else tocycle_mark_default
. Furthermore, processing of the recursive union will stop when a cycle has been detected.cycle_mark_value
andcycle_mark_default
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 Postgres Pro does not require that.) By default,TRUE
andFALSE
(of typeboolean
) are used. Furthermore, a column namedcycle_path_col_name
will be added to the result column list of theWITH
query. This column is used internally for tracking visited rows. SeeSection 7.8.2.2 for examples.
Both theSEARCH
and theCYCLE
clause are only valid for recursiveWITH
queries. Thewith_query
must be aUNION
(orUNION ALL
) of twoSELECT
(or equivalent) commands (no nestedUNION
s). If both clauses are used, the column added by theSEARCH
clause appears before the columns added by theCYCLE
clause.
The primary query and theWITH
queries are all (notionally) executed at the same time. This implies that the effects of a data-modifying statement inWITH
cannot be seen from other parts of the query, other than by reading itsRETURNING
output. If two such data-modifying statements attempt to modify the same row, the results are unspecified.
A key property ofWITH
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.
However, aWITH
query can be markedNOT MATERIALIZED
to remove this guarantee. In that case, theWITH
query can be folded into the primary query much as though it were a simple sub-SELECT
in the primary query'sFROM
clause. This results in duplicate computations if the primary query refers to thatWITH
query more than once; but if each such use requires only a few rows of theWITH
query's total output,NOT MATERIALIZED
can provide a net savings by allowing the queries to be optimized jointly.NOT MATERIALIZED
is ignored if it is attached to aWITH
query that is recursive or is not side-effect-free (i.e., is not a plainSELECT
containing no volatile functions).
By default, a side-effect-freeWITH
query is folded into the primary query if it is used exactly once in the primary query'sFROM
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 theWITH
query asMATERIALIZED
. That might be useful, for example, if theWITH
query is being used as an optimization fence to prevent the planner from choosing a bad plan.Postgres Pro versions before v12 never did such folding, so queries written for older versions might rely onWITH
to act as an optimization fence.
SeeSection 7.8 for additional information.
FROM
Clause#
TheFROM
clause specifies one or more source tables for theSELECT
. If multiple sources are specified, the result is the Cartesian product (cross join) of all the sources. But usually qualification conditions are added (viaWHERE
) to restrict the returned rows to a small subset of the Cartesian product.
TheFROM
clause can contain the following elements:
table_name
The name (optionally schema-qualified) of an existing table or view. If
ONLY
is specified before the table name, only that table is scanned. IfONLY
is not specified, the table and all its descendant tables (if any) are scanned. Optionally,*
can be specified after the table name to explicitly indicate that descendant tables are included.alias
A substitute name for the
FROM
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 givenFROM foo AS f
, the remainder of theSELECT
must refer to thisFROM
item asf
notfoo
. 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.TABLESAMPLE
sampling_method
(argument
[, ...] ) [ REPEATABLE (seed
) ]A
TABLESAMPLE
clause after atable_name
indicates that the specifiedsampling_method
should be used to retrieve a subset of the rows in that table. This sampling precedes the application of any other filters such asWHERE
clauses. The standardPostgres Pro distribution includes two sampling methods,BERNOULLI
andSYSTEM
, and other sampling methods can be installed in the database via extensions.The
BERNOULLI
andSYSTEM
sampling methods each accept a singleargument
which is the fraction of the table to sample, expressed as a percentage between 0 and 100. This argument can be anyreal
-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's rows. TheBERNOULLI
method scans the whole table and selects or ignores individual rows independently with the specified probability. TheSYSTEM
method does block-level sampling with each block having the specified chance of being selected; all rows in each selected block are returned. TheSYSTEM
method is significantly faster than theBERNOULLI
method when small sampling percentages are specified, but it may return a less-random sample of the table as a result of clustering effects.The optional
REPEATABLE
clause specifies aseed
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 andargument
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. IfREPEATABLE
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 acceptREPEATABLE
, and will always produce new samples on each use.select
A sub-
SELECT
can appear in theFROM
clause. This acts as though its output were created as a temporary table for the duration of this singleSELECT
command. Note that the sub-SELECT
must be surrounded by parentheses, and an alias can be provided in the same way as for a table. AVALUES
command can also be used here.with_query_name
A
WITH
query is referenced by writing its name, just as though the query's name were a table name. (In fact, theWITH
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's name.) An alias can be provided in the same way as for a table.function_name
Function calls can appear in the
FROM
clause. (This is especially useful for functions that return result sets, but any function can be used.) This acts as though the function's output were created as a temporary table for the duration of this singleSELECT
command. If the function's result type is composite (including the case of a function with multipleOUT
parameters), each attribute becomes a separate column in the implicit table.When the optional
WITH ORDINALITY
clause is added to the function call, an additional column of typebigint
will be appended to the function's result column(s). This column numbers the rows of the function's result set, starting from 1. By default, this column is namedordinality
.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's composite return type, including the ordinality column if present.
Multiple function calls can be combined into a single
FROM
-clause item by surrounding them withROWS 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.If the function has been defined as returning the
record
data type, then an alias or the key wordAS
must be present, followed by a column definition list in the form(
. The column definition list must match the actual number and types of columns returned by the function.column_name
data_type
[, ...])When using the
ROWS FROM( ... )
syntax, if one of the functions requires a column definition list, it's preferred to put the column definition list after the function call insideROWS FROM( ... )
. A column definition list can be placed after theROWS FROM( ... )
construct only if there's just a single function and noWITH ORDINALITY
clause.To use
ORDINALITY
together with a column definition list, you must use theROWS FROM( ... )
syntax and put the column definition list insideROWS FROM( ... )
.join_type
One of
[ INNER ] JOIN
LEFT [ OUTER ] JOIN
RIGHT [ OUTER ] JOIN
FULL [ OUTER ] JOIN
For the
INNER
andOUTER
join types, a join condition must be specified, namely exactly one ofON
,join_condition
USING (
, orjoin_column
[, ...])NATURAL
. See below for the meaning.A
JOIN
clause combines twoFROM
items, which for convenience we will refer to as“tables”, though in reality they can be any type ofFROM
item. Use parentheses if necessary to determine the order of nesting. In the absence of parentheses,JOIN
s nest left-to-right. In any caseJOIN
binds more tightly than the commas separatingFROM
-list items. All theJOIN
options are just a notational convenience, since they do nothing you couldn't do with plainFROM
andWHERE
.LEFT OUTER JOIN
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 theJOIN
clause's own condition is considered while deciding which rows have matches. Outer conditions are applied afterwards.Conversely,
RIGHT OUTER JOIN
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 aLEFT OUTER JOIN
by switching the left and right tables.FULL OUTER JOIN
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).ON
join_condition
join_condition
is an expression resulting in a value of typeboolean
(similar to aWHERE
clause) that specifies which rows in a join are considered to match.USING (
join_column
[, ...] ) [ ASjoin_using_alias
]A clause of the form
USING ( a, b, ... )
is shorthand forON left_table.a = right_table.a AND left_table.b = right_table.b ...
. Also,USING
implies that only one of each pair of equivalent columns will be included in the join output, not both.If a
join_using_alias
name is specified, it provides a table alias for the join columns. Only the join columns listed in theUSING
clause are addressable by this name. Unlike a regularalias
, this does not hide the names of the joined tables from the rest of the query. Also unlike a regularalias
, you cannot write a column alias list — the output names of the join columns are the same as they appear in theUSING
list.NATURAL
NATURAL
is shorthand for aUSING
list that mentions all columns in the two tables that have matching names. If there are no common column names,NATURAL
is equivalent toON TRUE
.CROSS JOIN
CROSS JOIN
is equivalent toINNER 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 ofFROM
, but restricted by the join condition (if any).LATERAL
The
LATERAL
key word can precede a sub-SELECT
FROM
item. This allows the sub-SELECT
to refer to columns ofFROM
items that appear before it in theFROM
list. (WithoutLATERAL
, each sub-SELECT
is evaluated independently and so cannot cross-reference any otherFROM
item.)LATERAL
can also precede a function-callFROM
item, but in this case it is a noise word, because the function expression can refer to earlierFROM
items in any case.A
LATERAL
item can appear at top level in theFROM
list, or within aJOIN
tree. In the latter case it can also refer to any items that are on the left-hand side of aJOIN
that it is on the right-hand side of.When a
FROM
item containsLATERAL
cross-references, evaluation proceeds as follows: for each row of theFROM
item providing the cross-referenced column(s), or set of rows of multipleFROM
items providing the columns, theLATERAL
item is evaluated using that row or row set's 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).The column source table(s) must be
INNER
orLEFT
joined to theLATERAL
item, else there would not be a well-defined set of rows from which to compute each set of rows for theLATERAL
item. Thus, although a construct such as
is syntactically valid, it is not actually allowed forX
RIGHT JOIN LATERALY
Y
to referenceX
.
WHERE
Clause#
The optionalWHERE
clause has the general form
WHEREcondition
wherecondition
is any expression that evaluates to a result of typeboolean
. 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.
GROUP BY
Clause#
The optionalGROUP BY
clause has the general form
GROUP BY [ ALL | DISTINCT ]grouping_element
[, ...]
GROUP BY
will condense into a single row all selected rows that share the same values for the grouped expressions. Anexpression
used inside agrouping_element
can be an input column name, or the name or ordinal number of an output column (SELECT
list item), or an arbitrary expression formed from input-column values. In case of ambiguity, aGROUP BY
name will be interpreted as an input-column name rather than an output column name.
If any ofGROUPING SETS
,ROLLUP
orCUBE
are present as grouping elements, then theGROUP BY
clause as a whole defines some number of independentgrouping sets
. The effect of this is equivalent to constructing aUNION ALL
between subqueries with the individual grouping sets as theirGROUP BY
clauses. The optionalDISTINCT
clause removes duplicate sets before processing; it doesnot transform theUNION ALL
into aUNION DISTINCT
. For further details on the handling of grouping sets seeSection 7.2.4.
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 noGROUP BY
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 aFILTER
clause to the aggregate function call; seeSection 4.2.7 for more information. When aFILTER
clause is present, only those rows matching it are included in the input to that aggregate function.
WhenGROUP BY
is present, or any aggregate functions are present, it is not valid for theSELECT
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.
Keep in mind that all aggregate functions are evaluated before evaluating any“scalar” expressions in theHAVING
clause orSELECT
list. This means that, for example, aCASE
expression cannot be used to skip evaluation of an aggregate function; seeSection 4.2.14.
Currently,FOR NO KEY UPDATE
,FOR UPDATE
,FOR SHARE
andFOR KEY SHARE
cannot be specified withGROUP BY
.
HAVING
Clause#
The optionalHAVING
clause has the general form
HAVINGcondition
wherecondition
is the same as specified for theWHERE
clause.
HAVING
eliminates group rows that do not satisfy the condition.HAVING
is different fromWHERE
:WHERE
filters individual rows before the application ofGROUP BY
, whileHAVING
filters group rows created byGROUP BY
. Each column referenced incondition
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.
The presence ofHAVING
turns a query into a grouped query even if there is noGROUP BY
clause. This is the same as what happens when the query contains aggregate functions but noGROUP BY
clause. All the selected rows are considered to form a single group, and theSELECT
list andHAVING
clause can only reference table columns from within aggregate functions. Such a query will emit a single row if theHAVING
condition is true, zero rows if it is not true.
Currently,FOR NO KEY UPDATE
,FOR UPDATE
,FOR SHARE
andFOR KEY SHARE
cannot be specified withHAVING
.
WINDOW
Clause#
The optionalWINDOW
clause has the general form
WINDOWwindow_name
AS (window_definition
) [, ...]
wherewindow_name
is a name that can be referenced fromOVER
clauses or subsequent window definitions, andwindow_definition
is
[existing_window_name
][ PARTITION BYexpression
[, ...] ][ ORDER BYexpression
[ ASC | DESC | USINGoperator
] [ NULLS { FIRST | LAST } ] [, ...] ][frame_clause
]
If anexisting_window_name
is specified it must refer to an earlier entry in theWINDOW
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 ownPARTITION BY
clause, and it can specifyORDER BY
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.
The elements of thePARTITION BY
list are interpreted in much the same fashion as elements of aGROUP BY
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 regularGROUP BY
clause. They are allowed here because windowing occurs after grouping and aggregation.
Similarly, the elements of theORDER BY
list are interpreted in much the same fashion as elements of a statement-levelORDER BY
clause, except that the expressions are always taken as simple expressions and never the name or number of an output column.
The optionalframe_clause
defines thewindow frame 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 thecurrent row). Theframe_clause
can be one of
{ RANGE | ROWS | GROUPS }frame_start
[frame_exclusion
]{ RANGE | ROWS | GROUPS } BETWEENframe_start
ANDframe_end
[frame_exclusion
]
whereframe_start
andframe_end
can be one of
UNBOUNDED PRECEDINGoffset
PRECEDINGCURRENT ROWoffset
FOLLOWINGUNBOUNDED FOLLOWING
andframe_exclusion
can be one of
EXCLUDE CURRENT ROWEXCLUDE GROUPEXCLUDE TIESEXCLUDE NO OTHERS
Ifframe_end
is omitted it defaults toCURRENT ROW
. Restrictions are thatframe_start
cannot beUNBOUNDED FOLLOWING
,frame_end
cannot beUNBOUNDED PRECEDING
, and theframe_end
choice cannot appear earlier in the above list offrame_start
andframe_end
options than theframe_start
choice does — for exampleRANGE BETWEEN CURRENT ROW AND
is not allowed.offset
PRECEDING
The default framing option isRANGE UNBOUNDED PRECEDING
, which is the same asRANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
; it sets the frame to be all rows from the partition start up through the current row's lastpeer (a row that the window'sORDER BY
clause considers equivalent to the current row; all rows are peers if there is noORDER BY
). In general,UNBOUNDED PRECEDING
means that the frame starts with the first row of the partition, and similarlyUNBOUNDED FOLLOWING
means that the frame ends with the last row of the partition, regardless ofRANGE
,ROWS
orGROUPS
mode. InROWS
mode,CURRENT ROW
means that the frame starts or ends with the current row; but inRANGE
orGROUPS
mode it means that the frame starts or ends with the current row's first or last peer in theORDER BY
ordering. Theoffset
PRECEDING
andoffset
FOLLOWING
options vary in meaning depending on the frame mode. InROWS
mode, theoffset
is an integer indicating that the frame starts or ends that many rows before or after the current row. InGROUPS
mode, theoffset
is an integer indicating that the frame starts or ends that many peer groups before or after the current row's peer group, where apeer group is a group of rows that are equivalent according to the window'sORDER BY
clause. InRANGE
mode, use of anoffset
option requires that there be exactly oneORDER BY
column in the window definition. Then the frame contains those rows whose ordering column value is no more thanoffset
less than (forPRECEDING
) or more than (forFOLLOWING
) the current row's ordering column value. In these cases the data type of theoffset
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 aninterval
. In all these cases, the value of theoffset
must be non-null and non-negative. Also, while theoffset
does not have to be a simple constant, it cannot contain variables, aggregate functions, or window functions.
Theframe_exclusion
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.EXCLUDE CURRENT ROW
excludes the current row from the frame.EXCLUDE GROUP
excludes the current row and its ordering peers from the frame.EXCLUDE TIES
excludes any peers of the current row from the frame, but not the current row itself.EXCLUDE NO OTHERS
simply specifies explicitly the default behavior of not excluding the current row or its peers.
Beware that theROWS
mode can produce unpredictable results if theORDER BY
ordering does not order the rows uniquely. TheRANGE
andGROUPS
modes are designed to ensure that rows that are peers in theORDER BY
ordering are treated alike: all rows of a given peer group will be in the frame or excluded from it.
The purpose of aWINDOW
clause is to specify the behavior ofwindow functions appearing in the query'sSELECT
list orORDER BY
clause. These functions can reference theWINDOW
clause entries by name in theirOVER
clauses. AWINDOW
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 anyWINDOW
clause at all, since a window function call can specify its window definition directly in itsOVER
clause. However, theWINDOW
clause saves typing when the same window definition is needed for more than one window function.
Currently,FOR NO KEY UPDATE
,FOR UPDATE
,FOR SHARE
andFOR KEY SHARE
cannot be specified withWINDOW
.
Window functions are described in detail inSection 3.5,Section 4.2.8, andSection 7.2.5.
SELECT
List#
TheSELECT
list (between the key wordsSELECT
andFROM
) specifies expressions that form the output rows of theSELECT
statement. The expressions can (and usually do) refer to columns computed in theFROM
clause.
Just as in a table, every output column of aSELECT
has a name. In a simpleSELECT
this name is just used to label the column for display, but when theSELECT
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, writeAS
output_name
after the column's expression. (You can omitAS
, but only if the desired output name does not match anyPostgres Pro keyword (seeAppendix C). For protection against possible future keyword additions, it is recommended that you always either writeAS
or double-quote the output name.) If you do not specify a column name, a name is chosen automatically byPostgres Pro. If the column's expression is a simple column reference then the chosen name is the same as that column's 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?column?
.
An output column's name can be used to refer to the column's value inORDER BY
andGROUP BY
clauses, but not in theWHERE
orHAVING
clauses; there you must write out the expression instead.
Instead of an expression,*
can be written in the output list as a shorthand for all the columns of the selected rows. Also, you can write
as a shorthand for the columns coming from just that table. In these cases it is not possible to specify new names withtable_name
.*AS
; the output column names will be the same as the table columns' names.
According to the SQL standard, the expressions in the output list should be computed before applyingDISTINCT
,ORDER BY
, orLIMIT
. This is obviously necessary when usingDISTINCT
, since otherwise it's not clear what values are being made distinct. However, in many cases it is convenient if output expressions are computed afterORDER BY
andLIMIT
; 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.Postgres Pro will effectively evaluate output expressions after sorting and limiting, so long as those expressions are not referenced inDISTINCT
,ORDER BY
orGROUP BY
. (As a counterexample,SELECT f(x) FROM tab ORDER BY 1
clearly must evaluatef(x)
before sorting.) Output expressions that contain set-returning functions are effectively evaluated after sorting and before limiting, so thatLIMIT
will act to cut off the output from a set-returning function.
Note
Postgres Pro 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.
DISTINCT
Clause#
IfSELECT DISTINCT
is specified, all duplicate rows are removed from the result set (one row is kept from each group of duplicates).SELECT ALL
specifies the opposite: all rows are kept; that is the default.
SELECT DISTINCT ON (
keeps only the first row of each set of rows where the given expressions evaluate to equal. Theexpression
[, ...] )DISTINCT ON
expressions are interpreted using the same rules as forORDER BY
(see above). Note that the“first row” of each set is unpredictable unlessORDER BY
is used to ensure that the desired row appears first. For example:
SELECT DISTINCT ON (location) location, time, report FROM weather_reports ORDER BY location, time DESC;
retrieves the most recent weather report for each location. But if we had not usedORDER BY
to force descending order of time values for each location, we'd have gotten a report from an unpredictable time for each location.
TheDISTINCT ON
expression(s) must match the leftmostORDER BY
expression(s). TheORDER BY
clause will normally contain additional expression(s) that determine the desired precedence of rows within eachDISTINCT ON
group.
Currently,FOR NO KEY UPDATE
,FOR UPDATE
,FOR SHARE
andFOR KEY SHARE
cannot be specified withDISTINCT
.
UNION
Clause#
TheUNION
clause has this general form:
select_statement
UNION [ ALL | DISTINCT ]select_statement
select_statement
is anySELECT
statement without anORDER BY
,LIMIT
,FOR NO KEY UPDATE
,FOR UPDATE
,FOR SHARE
, orFOR KEY SHARE
clause. (ORDER BY
andLIMIT
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 theUNION
, not to its right-hand input expression.)
TheUNION
operator computes the set union of the rows returned by the involvedSELECT
statements. A row is in the set union of two result sets if it appears in at least one of the result sets. The twoSELECT
statements that represent the direct operands of theUNION
must produce the same number of columns, and corresponding columns must be of compatible data types.
The result ofUNION
does not contain any duplicate rows unless theALL
option is specified.ALL
prevents elimination of duplicates. (Therefore,UNION ALL
is usually significantly quicker thanUNION
; useALL
when you can.)DISTINCT
can be written to explicitly specify the default behavior of eliminating duplicate rows.
MultipleUNION
operators in the sameSELECT
statement are evaluated left to right, unless otherwise indicated by parentheses.
Currently,FOR NO KEY UPDATE
,FOR UPDATE
,FOR SHARE
andFOR KEY SHARE
cannot be specified either for aUNION
result or for any input of aUNION
.
INTERSECT
Clause#
TheINTERSECT
clause has this general form:
select_statement
INTERSECT [ ALL | DISTINCT ]select_statement
select_statement
is anySELECT
statement without anORDER BY
,LIMIT
,FOR NO KEY UPDATE
,FOR UPDATE
,FOR SHARE
, orFOR KEY SHARE
clause.
TheINTERSECT
operator computes the set intersection of the rows returned by the involvedSELECT
statements. A row is in the intersection of two result sets if it appears in both result sets.
The result ofINTERSECT
does not contain any duplicate rows unless theALL
option is specified. WithALL
, a row that hasm
duplicates in the left table andn
duplicates in the right table will appear min(m
,n
) times in the result set.DISTINCT
can be written to explicitly specify the default behavior of eliminating duplicate rows.
MultipleINTERSECT
operators in the sameSELECT
statement are evaluated left to right, unless parentheses dictate otherwise.INTERSECT
binds more tightly thanUNION
. That is,A UNION B INTERSECT C
will be read asA UNION (B INTERSECT C)
.
Currently,FOR NO KEY UPDATE
,FOR UPDATE
,FOR SHARE
andFOR KEY SHARE
cannot be specified either for anINTERSECT
result or for any input of anINTERSECT
.
EXCEPT
Clause#
TheEXCEPT
clause has this general form:
select_statement
EXCEPT [ ALL | DISTINCT ]select_statement
select_statement
is anySELECT
statement without anORDER BY
,LIMIT
,FOR NO KEY UPDATE
,FOR UPDATE
,FOR SHARE
, orFOR KEY SHARE
clause.
TheEXCEPT
operator computes the set of rows that are in the result of the leftSELECT
statement but not in the result of the right one.
The result ofEXCEPT
does not contain any duplicate rows unless theALL
option is specified. WithALL
, a row that hasm
duplicates in the left table andn
duplicates in the right table will appear max(m
-n
,0) times in the result set.DISTINCT
can be written to explicitly specify the default behavior of eliminating duplicate rows.
MultipleEXCEPT
operators in the sameSELECT
statement are evaluated left to right, unless parentheses dictate otherwise.EXCEPT
binds at the same level asUNION
.
Currently,FOR NO KEY UPDATE
,FOR UPDATE
,FOR SHARE
andFOR KEY SHARE
cannot be specified either for anEXCEPT
result or for any input of anEXCEPT
.
ORDER BY
Clause#
The optionalORDER BY
clause has this general form:
ORDER BYexpression
[ ASC | DESC | USINGoperator
] [ NULLS { FIRST | LAST } ] [, ...]
TheORDER BY
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.
Eachexpression
can be the name or ordinal number of an output column (SELECT
list item), or it can be an arbitrary expression formed from input-column values.
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 theAS
clause.
It is also possible to use arbitrary expressions in theORDER BY
clause, including columns that do not appear in theSELECT
output list. Thus the following statement is valid:
SELECT name FROM distributors ORDER BY code;
A limitation of this feature is that anORDER BY
clause applying to the result of aUNION
,INTERSECT
, orEXCEPT
clause can only specify an output column name or number, not an expression.
If anORDER BY
expression is a simple name that matches both an output column name and an input column name,ORDER BY
will interpret it as the output column name. This is the opposite of the choice thatGROUP BY
will make in the same situation. This inconsistency is made to be compatible with the SQL standard.
Optionally one can add the key wordASC
(ascending) orDESC
(descending) after any expression in theORDER BY
clause. If not specified,ASC
is assumed by default. Alternatively, a specific ordering operator name can be specified in theUSING
clause. An ordering operator must be a less-than or greater-than member of some B-tree operator family.ASC
is usually equivalent toUSING <
andDESC
is usually equivalent toUSING >
. (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.)
IfNULLS LAST
is specified, null values sort after all non-null values; ifNULLS FIRST
is specified, null values sort before all non-null values. If neither is specified, the default behavior isNULLS LAST
whenASC
is specified or implied, andNULLS FIRST
whenDESC
is specified (thus, the default is to act as though nulls are larger than non-nulls). WhenUSING
is specified, the default nulls ordering depends on whether the operator is a less-than or greater-than operator.
Note that ordering options apply only to the expression they follow; for exampleORDER BY x, y DESC
does not mean the same thing asORDER BY x DESC, y DESC
.
Character-string data is sorted according to the collation that applies to the column being sorted. That can be overridden at need by including aCOLLATE
clause in theexpression
, for exampleORDER BY mycolumn COLLATE "en_US"
. For more information seeSection 4.2.10 andSection 22.2.
LIMIT
Clause#
TheLIMIT
clause consists of two independent sub-clauses:
LIMIT {count
| ALL }OFFSETstart
The parametercount
specifies the maximum number of rows to return, whilestart
specifies the number of rows to skip before starting to return rows. When both are specified,start
rows are skipped before starting to count thecount
rows to be returned.
If thecount
expression evaluates to NULL, it is treated asLIMIT ALL
, i.e., no limit. Ifstart
evaluates to NULL, it is treated the same asOFFSET 0
.
SQL:2008 introduced a different syntax to achieve the same result, whichPostgres Pro also supports. It is:
OFFSETstart
{ ROW | ROWS }FETCH { FIRST | NEXT } [count
] { ROW | ROWS } { ONLY | WITH TIES }
In this syntax, thestart
orcount
value is required by the standard to be a literal constant, a parameter, or a variable name; as aPostgres Pro extension, other expressions are allowed, but will generally need to be enclosed in parentheses to avoid ambiguity. Ifcount
is omitted in aFETCH
clause, it defaults to 1. TheWITH TIES
option is used to return any additional rows that tie for the last place in the result set according to theORDER BY
clause;ORDER BY
is mandatory in this case, andSKIP LOCKED
is not allowed.ROW
andROWS
as well asFIRST
andNEXT
are noise words that don't influence the effects of these clauses. According to the standard, theOFFSET
clause must come before theFETCH
clause if both are present; butPostgres Pro is laxer and allows either order.
When usingLIMIT
, it is a good idea to use anORDER BY
clause that constrains the result rows into a unique order. Otherwise you will get an unpredictable subset of the query's rows — you might be asking for the tenth through twentieth rows, but tenth through twentieth in what ordering? You don't know what ordering unless you specifyORDER BY
.
The query planner takesLIMIT
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 forLIMIT
andOFFSET
. Thus, using differentLIMIT
/OFFSET
values to select different subsets of a query resultwill give inconsistent results unless you enforce a predictable result ordering withORDER 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 unlessORDER BY
is used to constrain the order.
It is even possible for repeated executions of the sameLIMIT
query to return different subsets of the rows of a table, if there is not anORDER BY
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.
The Locking Clause#
FOR UPDATE
,FOR NO KEY UPDATE
,FOR SHARE
andFOR KEY SHARE
arelocking clauses; they affect howSELECT
locks rows as they are obtained from the table.
The locking clause has the general form
FORlock_strength
[ OFfrom_reference
[, ...] ] [ NOWAIT | SKIP LOCKED ]
wherelock_strength
can be one of
UPDATENO KEY UPDATESHAREKEY SHARE
from_reference
must be a tablealias
or non-hiddentable_name
referenced in theFROM
clause. For more information on each row-level lock mode, refer toSection 13.3.2.
To prevent the operation from waiting for other transactions to commit, use either theNOWAIT
orSKIP LOCKED
option. WithNOWAIT
, the statement reports an error, rather than waiting, if a selected row cannot be locked immediately. WithSKIP 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 thatNOWAIT
andSKIP LOCKED
apply only to the row-level lock(s) — the requiredROW SHARE
table-level lock is still taken in the ordinary way (seeChapter 13). You can useLOCK
with theNOWAIT
option first, if you need to acquire the table-level lock without waiting.
If specific tables are named in a locking clause, then only rows coming from those tables are locked; any other tables used in theSELECT
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 toWITH
queries referenced by the primary query. If you want row locking to occur within aWITH
query, specify a locking clause within theWITH
query.
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 asNOWAIT
if that is specified in any of the clauses affecting it. Otherwise, it is processed asSKIP LOCKED
if that is specified in any of the clauses affecting it.
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.
When a locking clause appears at the top level of aSELECT
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 aLIMIT
is used, locking stops once enough rows have been returned to satisfy the limit (but note that rows skipped over byOFFSET
will get locked). Similarly, if a locking clause is used in a cursor's query, only rows actually fetched or stepped past by the cursor will be locked.
When a locking clause appears in a sub-SELECT
, 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,
SELECT * FROM (SELECT * FROM mytable FOR UPDATE) ss WHERE col1 = 5;
will lock only rows havingcol1 = 5
, even though that condition is not textually within the sub-query.
Previous releases failed to preserve a lock which is upgraded by a later savepoint. For example, this code:
BEGIN;SELECT * FROM mytable WHERE key = 1 FOR UPDATE;SAVEPOINT s;UPDATE mytable SET ... WHERE key = 1;ROLLBACK TO s;
would fail to preserve theFOR UPDATE
lock after theROLLBACK TO
. This has been fixed in release 9.3.
Caution
It is possible for aSELECT
command running at theREAD COMMITTED
transaction isolation level and usingORDER BY
and a locking clause to return rows out of order. This is becauseORDER BY
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 theSELECT
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 theFOR UPDATE/SHARE
clause in a sub-query, for example
SELECT * FROM (SELECT * FROM mytable FOR UPDATE) ss ORDER BY column1;
Note that this will result in locking all rows ofmytable
, whereasFOR UPDATE
at the top level would lock only the actually returned rows. This can make for a significant performance difference, particularly if theORDER BY
is combined withLIMIT
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.
At theREPEATABLE READ
orSERIALIZABLE
transaction isolation level this would cause a serialization failure (with anSQLSTATE
of'40001'
), so there is no possibility of receiving rows out of order under these isolation levels.
TABLE
Command#
The command
TABLEname
is equivalent to
SELECT * FROMname
It can be used as a top-level command or as a space-saving syntax variant in parts of complex queries. Only theWITH
,UNION
,INTERSECT
,EXCEPT
,ORDER BY
,LIMIT
,OFFSET
,FETCH
andFOR
locking clauses can be used withTABLE
; theWHERE
clause and any form of aggregation cannot be used.
Examples
To join the tablefilms
with the tabledistributors
:
SELECT f.title, f.did, d.name, f.date_prod, f.kind FROM distributors d JOIN films f USING (did); title | did | name | date_prod | kind-------------------+-----+--------------+------------+---------- The Third Man | 101 | British Lion | 1949-12-23 | Drama The African Queen | 101 | British Lion | 1951-08-11 | Romantic ...
To sum the columnlen
of all films and group the results bykind
:
SELECT kind, sum(len) AS total FROM films GROUP BY kind; kind | total----------+------- Action | 07:34 Comedy | 02:58 Drama | 14:28 Musical | 06:42 Romantic | 04:38
To sum the columnlen
of all films, group the results bykind
and show those group totals that are less than 5 hours:
SELECT kind, sum(len) AS total FROM films GROUP BY kind HAVING sum(len) < interval '5 hours'; kind | total----------+------- Comedy | 02:58 Romantic | 04:38
The following two examples are identical ways of sorting the individual results according to the contents of the second column (name
):
SELECT * FROM distributors ORDER BY name;SELECT * FROM distributors ORDER BY 2; did | name-----+------------------ 109 | 20th Century Fox 110 | Bavaria Atelier 101 | British Lion 107 | Columbia 102 | Jean Luc Godard 113 | Luso films 104 | Mosfilm 103 | Paramount 106 | Toho 105 | United Artists 111 | Walt Disney 112 | Warner Bros. 108 | Westward
The next example shows how to obtain the union of the tablesdistributors
andactors
, restricting the results to those that begin with the letter W in each table. Only distinct rows are wanted, so the key wordALL
is omitted.
distributors: actors: did | name id | name-----+-------------- ----+---------------- 108 | Westward 1 | Woody Allen 111 | Walt Disney 2 | Warren Beatty 112 | Warner Bros. 3 | Walter Matthau ... ...SELECT distributors.name FROM distributors WHERE distributors.name LIKE 'W%'UNIONSELECT actors.name FROM actors WHERE actors.name LIKE 'W%'; name---------------- Walt Disney Walter Matthau Warner Bros. Warren Beatty Westward Woody Allen
This example shows how to use a function in theFROM
clause, both with and without a column definition list:
CREATE FUNCTION distributors(int) RETURNS SETOF distributors AS $$ SELECT * FROM distributors WHERE did = $1;$$ LANGUAGE SQL;SELECT * FROM distributors(111); did | name-----+------------- 111 | Walt DisneyCREATE FUNCTION distributors_2(int) RETURNS SETOF record AS $$ SELECT * FROM distributors WHERE did = $1;$$ LANGUAGE SQL;SELECT * FROM distributors_2(111) AS (f1 int, f2 text); f1 | f2-----+------------- 111 | Walt Disney
Here is an example of a function with an ordinality column added:
SELECT * FROM unnest(ARRAY['a','b','c','d','e','f']) WITH ORDINALITY; unnest | ordinality--------+---------- a | 1 b | 2 c | 3 d | 4 e | 5 f | 6(6 rows)
This example shows how to use a simpleWITH
clause:
WITH t AS ( SELECT random() as x FROM generate_series(1, 3) )SELECT * FROM tUNION ALLSELECT * FROM t; x-------------------- 0.534150459803641 0.520092216785997 0.0735620250925422 0.534150459803641 0.520092216785997 0.0735620250925422
Notice that theWITH
query was evaluated only once, so that we got two sets of the same three random values.
This example usesWITH RECURSIVE
to find all subordinates (direct or indirect) of the employee Mary, and their level of indirectness, from a table that shows only direct subordinates:
WITH RECURSIVE employee_recursive(distance, employee_name, manager_name) AS ( SELECT 1, employee_name, manager_name FROM employee WHERE manager_name = 'Mary' UNION ALL SELECT er.distance + 1, e.employee_name, e.manager_name FROM employee_recursive er, employee e WHERE er.employee_name = e.manager_name )SELECT distance, employee_name FROM employee_recursive;
Notice the typical form of recursive queries: an initial condition, followed byUNION
, 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. (SeeSection 7.8 for more examples.)
This example usesLATERAL
to apply a set-returning functionget_product_names()
for each row of themanufacturers
table:
SELECT m.name AS mname, pnameFROM manufacturers m, LATERAL get_product_names(m.id) pname;
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:
SELECT m.name AS mname, pnameFROM manufacturers m LEFT JOIN LATERAL get_product_names(m.id) pname ON true;
Compatibility
Of course, theSELECT
statement is compatible with the SQL standard. But there are some extensions and some missing features.
OmittedFROM
Clauses
Postgres Pro allows one to omit theFROM
clause. It has a straightforward use to compute the results of simple expressions:
SELECT 2+2; ?column?---------- 4
Some otherSQL databases cannot do this except by introducing a dummy one-row table from which to do theSELECT
.
EmptySELECT
Lists
The list of output expressions afterSELECT
can be empty, producing a zero-column result table. This is not valid syntax according to the SQL standard.Postgres Pro allows it to be consistent with allowing zero-column tables. However, an empty list is not allowed whenDISTINCT
is used.
Omitting theAS
Key Word
In the SQL standard, the optional key wordAS
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).Postgres Pro is slightly more restrictive:AS
is required if the new column name matches any keyword at all, reserved or not. Recommended practice is to useAS
or double-quote output column names, to prevent any possible conflict against future keyword additions.
InFROM
items, both the standard andPostgres Pro allowAS
to be omitted before an alias that is an unreserved keyword. But this is impractical for output column names, because of syntactic ambiguities.
Omitting Sub-SELECT
Aliases inFROM
According to the SQL standard, a sub-SELECT
in theFROM
list must have an alias. InPostgres Pro, this alias may be omitted.
ONLY
and Inheritance
The SQL standard requires parentheses around the table name when writingONLY
, for exampleSELECT * FROM ONLY (tab1), ONLY (tab2) WHERE ...
.Postgres Pro considers these parentheses to be optional.
Postgres Pro allows a trailing*
to be written to explicitly specify the non-ONLY
behavior of including child tables. The standard does not allow this.
(These points apply equally to all SQL commands supporting theONLY
option.)
TABLESAMPLE
Clause Restrictions
TheTABLESAMPLE
clause is currently accepted only on regular tables and materialized views. According to the SQL standard it should be possible to apply it to anyFROM
item.
Function Calls inFROM
Postgres Pro allows a function call to be written directly as a member of theFROM
list. In the SQL standard it would be necessary to wrap such a function call in a sub-SELECT
; that is, the syntaxFROM
is approximately equivalent tofunc
(...)alias
FROM LATERAL (SELECT
. Note thatfunc
(...))alias
LATERAL
is considered to be implicit; this is because the standard requiresLATERAL
semantics for anUNNEST()
item inFROM
.Postgres Pro treatsUNNEST()
the same as other set-returning functions.
Namespace Available toGROUP BY
andORDER BY
In the SQL-92 standard, anORDER BY
clause can only use output column names or numbers, while aGROUP BY
clause can only use expressions based on input column names.Postgres Pro extends each of these clauses to allow the other choice as well (but it uses the standard's interpretation if there is ambiguity).Postgres Pro 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.
SQL:1999 and later use a slightly different definition which is not entirely upward compatible with SQL-92. In most cases, however,Postgres Pro will interpret anORDER BY
orGROUP BY
expression the same way SQL:1999 does.
Functional Dependencies
Postgres Pro recognizes functional dependency (allowing columns to be omitted fromGROUP BY
) only when a table's primary key is included in theGROUP BY
list. The SQL standard specifies additional conditions that should be recognized.
LIMIT
andOFFSET
The clausesLIMIT
andOFFSET
arePostgres Pro-specific syntax, also used byMySQL. The SQL:2008 standard has introduced the clausesOFFSET ... FETCH {FIRST|NEXT} ...
for the same functionality, as shown above inLIMIT Clause. This syntax is also used byIBM DB2. (Applications written forOracle frequently use a workaround involving the automatically generatedrownum
column, which is not available in Postgres Pro, to implement the effects of these clauses.)
FOR NO KEY UPDATE
,FOR UPDATE
,FOR SHARE
,FOR KEY SHARE
AlthoughFOR UPDATE
appears in the SQL standard, the standard allows it only as an option ofDECLARE CURSOR
.Postgres Pro allows it in anySELECT
query as well as in sub-SELECT
s, but this is an extension. TheFOR NO KEY UPDATE
,FOR SHARE
andFOR KEY SHARE
variants, as well as theNOWAIT
andSKIP LOCKED
options, do not appear in the standard.
Data-Modifying Statements inWITH
Postgres Pro allowsINSERT
,UPDATE
,DELETE
, andMERGE
to be used asWITH
queries. This is not found in the SQL standard.
Nonstandard Clauses
DISTINCT ON ( ... )
is an extension of the SQL standard.
ROWS FROM( ... )
is an extension of the SQL standard.
TheMATERIALIZED
andNOT MATERIALIZED
options ofWITH
are extensions of the SQL standard.