4 SELECT, TABLE, WITH — retrieve rows from a table or view
8 [ WITH [ RECURSIVE ] with_query [, ...] ]
9 SELECT [ ALL | DISTINCT [ ON ( expression [, ...] ) ] ]
10 [ { * | expression [ [ AS ] output_name ] } [, ...] ]
11 [ FROM from_item [, ...] ]
13 [ GROUP BY [ ALL | DISTINCT ] grouping_element [, ...] ]
15 [ WINDOW window_name AS ( window_definition ) [, ...] ]
16 [ { UNION | INTERSECT | EXCEPT } [ ALL | DISTINCT ] select ]
17 [ ORDER BY expression [ ASC | DESC | USING operator ] [ NULLS { FIRST | LAST
19 [ LIMIT { count | ALL } ]
20 [ OFFSET start [ ROW | ROWS ] ]
21 [ FETCH { FIRST | NEXT } [ count ] { ROW | ROWS } { ONLY | WITH TIES } ]
22 [ FOR { UPDATE | NO KEY UPDATE | SHARE | KEY SHARE } [ OF from_reference [,
23 ...] ] [ NOWAIT | SKIP LOCKED ] [...] ]
25 where from_item can be one of:
27 [ ONLY ] table_name [ * ] [ [ AS ] alias [ ( column_alias [, ...] ) ] ]
28 [ TABLESAMPLE sampling_method ( argument [, ...] ) [ REPEATABLE
30 [ LATERAL ] ( select ) [ [ AS ] alias [ ( column_alias [, ...] ) ] ]
31 with_query_name [ [ AS ] alias [ ( column_alias [, ...] ) ] ]
32 [ LATERAL ] function_name ( [ argument [, ...] ] )
33 [ WITH ORDINALITY ] [ [ AS ] alias [ ( column_alias [, ...] ) ]
35 [ LATERAL ] function_name ( [ argument [, ...] ] ) [ AS ] alias ( column_def
37 [ LATERAL ] function_name ( [ argument [, ...] ] ) AS ( column_definition [,
39 [ LATERAL ] ROWS FROM( function_name ( [ argument [, ...] ] ) [ AS ( column_
40 definition [, ...] ) ] [, ...] )
41 [ WITH ORDINALITY ] [ [ AS ] alias [ ( column_alias [, ...] ) ]
43 from_item join_type from_item { ON join_condition | USING ( join_column [, .
44 ..] ) [ AS join_using_alias ] }
45 from_item NATURAL join_type from_item
46 from_item CROSS JOIN from_item
48 and grouping_element can be one of:
52 ( expression [, ...] )
53 ROLLUP ( { expression | ( expression [, ...] ) } [, ...] )
54 CUBE ( { expression | ( expression [, ...] ) } [, ...] )
55 GROUPING SETS ( grouping_element [, ...] )
59 with_query_name [ ( column_name [, ...] ) ] AS [ [ NOT ] MATERIALIZED ] ( se
60 lect | values | insert | update | delete | merge )
61 [ SEARCH { BREADTH | DEPTH } FIRST BY column_name [, ...] SET search_seq
63 [ CYCLE column_name [, ...] SET cycle_mark_col_name [ TO cycle_mark_valu
64 e DEFAULT cycle_mark_default ] USING cycle_path_col_name ]
66 TABLE [ ONLY ] table_name [ * ]
70 SELECT retrieves rows from zero or more tables. The general processing
71 of SELECT is as follows:
72 1. All queries in the WITH list are computed. These effectively serve
73 as temporary tables that can be referenced in the FROM list. A WITH
74 query that is referenced more than once in FROM is computed only
75 once, unless specified otherwise with NOT MATERIALIZED. (See WITH
77 2. All elements in the FROM list are computed. (Each element in the
78 FROM list is a real or virtual table.) If more than one element is
79 specified in the FROM list, they are cross-joined together. (See
81 3. If the WHERE clause is specified, all rows that do not satisfy the
82 condition are eliminated from the output. (See WHERE Clause below.)
83 4. If the GROUP BY clause is specified, or if there are aggregate
84 function calls, the output is combined into groups of rows that
85 match on one or more values, and the results of aggregate functions
86 are computed. If the HAVING clause is present, it eliminates groups
87 that do not satisfy the given condition. (See GROUP BY Clause and
88 HAVING Clause below.) Although query output columns are nominally
89 computed in the next step, they can also be referenced (by name or
90 ordinal number) in the GROUP BY clause.
91 5. The actual output rows are computed using the SELECT output
92 expressions for each selected row or row group. (See SELECT List
94 6. SELECT DISTINCT eliminates duplicate rows from the result. SELECT
95 DISTINCT ON eliminates rows that match on all the specified
96 expressions. SELECT ALL (the default) will return all candidate
97 rows, including duplicates. (See DISTINCT Clause below.)
98 7. Using the operators UNION, INTERSECT, and EXCEPT, the output of
99 more than one SELECT statement can be combined to form a single
100 result set. The UNION operator returns all rows that are in one or
101 both of the result sets. The INTERSECT operator returns all rows
102 that are strictly in both result sets. The EXCEPT operator returns
103 the rows that are in the first result set but not in the second. In
104 all three cases, duplicate rows are eliminated unless ALL is
105 specified. The noise word DISTINCT can be added to explicitly
106 specify eliminating duplicate rows. Notice that DISTINCT is the
107 default behavior here, even though ALL is the default for SELECT
108 itself. (See UNION Clause, INTERSECT Clause, and EXCEPT Clause
110 8. If the ORDER BY clause is specified, the returned rows are sorted
111 in the specified order. If ORDER BY is not given, the rows are
112 returned in whatever order the system finds fastest to produce.
113 (See ORDER BY Clause below.)
114 9. If the LIMIT (or FETCH FIRST) or OFFSET clause is specified, the
115 SELECT statement only returns a subset of the result rows. (See
117 10. If FOR UPDATE, FOR NO KEY UPDATE, FOR SHARE or FOR KEY SHARE is
118 specified, the SELECT statement locks the selected rows against
119 concurrent updates. (See The Locking Clause below.)
121 You must have SELECT privilege on each column used in a SELECT command.
122 The use of FOR NO KEY UPDATE, FOR UPDATE, FOR SHARE or FOR KEY SHARE
123 requires UPDATE privilege as well (for at least one column of each
130 The WITH clause allows you to specify one or more subqueries that can
131 be referenced by name in the primary query. The subqueries effectively
132 act as temporary tables or views for the duration of the primary query.
133 Each subquery can be a SELECT, TABLE, VALUES, INSERT, UPDATE, DELETE,
134 or MERGE statement. When writing a data-modifying statement (INSERT,
135 UPDATE, DELETE, or MERGE) in WITH, it is usual to include a RETURNING
136 clause. It is the output of RETURNING, not the underlying table that
137 the statement modifies, that forms the temporary table that is read by
138 the primary query. If RETURNING is omitted, the statement is still
139 executed, but it produces no output so it cannot be referenced as a
140 table by the primary query.
142 A name (without schema qualification) must be specified for each WITH
143 query. Optionally, a list of column names can be specified; if this is
144 omitted, the column names are inferred from the subquery.
146 If RECURSIVE is specified, it allows a SELECT subquery to reference
147 itself by name. Such a subquery must have the form
148 non_recursive_term UNION [ ALL | DISTINCT ] recursive_term
150 where the recursive self-reference must appear on the right-hand side
151 of the UNION. Only one recursive self-reference is permitted per query.
152 Recursive data-modifying statements are not supported, but you can use
153 the results of a recursive SELECT query in a data-modifying statement.
154 See Section 7.8 for an example.
156 Another effect of RECURSIVE is that WITH queries need not be ordered: a
157 query can reference another one that is later in the list. (However,
158 circular references, or mutual recursion, are not implemented.) Without
159 RECURSIVE, WITH queries can only reference sibling WITH queries that
160 are earlier in the WITH list.
162 When there are multiple queries in the WITH clause, RECURSIVE should be
163 written only once, immediately after WITH. It applies to all queries in
164 the WITH clause, though it has no effect on queries that do not use
165 recursion or forward references.
167 The optional SEARCH clause computes a search sequence column that can
168 be used for ordering the results of a recursive query in either
169 breadth-first or depth-first order. The supplied column name list
170 specifies the row key that is to be used for keeping track of visited
171 rows. A column named search_seq_col_name will be added to the result
172 column list of the WITH query. This column can be ordered by in the
173 outer query to achieve the respective ordering. See Section 7.8.2.1 for
176 The optional CYCLE clause is used to detect cycles in recursive
177 queries. The supplied column name list specifies the row key that is to
178 be used for keeping track of visited rows. A column named
179 cycle_mark_col_name will be added to the result column list of the WITH
180 query. This column will be set to cycle_mark_value when a cycle has
181 been detected, else to cycle_mark_default. Furthermore, processing of
182 the recursive union will stop when a cycle has been detected.
183 cycle_mark_value and cycle_mark_default must be constants and they must
184 be coercible to a common data type, and the data type must have an
185 inequality operator. (The SQL standard requires that they be Boolean
186 constants or character strings, but PostgreSQL does not require that.)
187 By default, TRUE and FALSE (of type boolean) are used. Furthermore, a
188 column named cycle_path_col_name will be added to the result column
189 list of the WITH query. This column is used internally for tracking
190 visited rows. See Section 7.8.2.2 for examples.
192 Both the SEARCH and the CYCLE clause are only valid for recursive WITH
193 queries. The with_query must be a UNION (or UNION ALL) of two SELECT
194 (or equivalent) commands (no nested UNIONs). If both clauses are used,
195 the column added by the SEARCH clause appears before the columns added
198 The primary query and the WITH queries are all (notionally) executed at
199 the same time. This implies that the effects of a data-modifying
200 statement in WITH cannot be seen from other parts of the query, other
201 than by reading its RETURNING output. If two such data-modifying
202 statements attempt to modify the same row, the results are unspecified.
204 A key property of WITH queries is that they are normally evaluated only
205 once per execution of the primary query, even if the primary query
206 refers to them more than once. In particular, data-modifying statements
207 are guaranteed to be executed once and only once, regardless of whether
208 the primary query reads all or any of their output.
210 However, a WITH query can be marked NOT MATERIALIZED to remove this
211 guarantee. In that case, the WITH query can be folded into the primary
212 query much as though it were a simple sub-SELECT in the primary query's
213 FROM clause. This results in duplicate computations if the primary
214 query refers to that WITH query more than once; but if each such use
215 requires only a few rows of the WITH query's total output, NOT
216 MATERIALIZED can provide a net savings by allowing the queries to be
217 optimized jointly. NOT MATERIALIZED is ignored if it is attached to a
218 WITH query that is recursive or is not side-effect-free (i.e., is not a
219 plain SELECT containing no volatile functions).
221 By default, a side-effect-free WITH query is folded into the primary
222 query if it is used exactly once in the primary query's FROM clause.
223 This allows joint optimization of the two query levels in situations
224 where that should be semantically invisible. However, such folding can
225 be prevented by marking the WITH query as MATERIALIZED. That might be
226 useful, for example, if the WITH query is being used as an optimization
227 fence to prevent the planner from choosing a bad plan. PostgreSQL
228 versions before v12 never did such folding, so queries written for
229 older versions might rely on WITH to act as an optimization fence.
231 See Section 7.8 for additional information.
235 The FROM clause specifies one or more source tables for the SELECT. If
236 multiple sources are specified, the result is the Cartesian product
237 (cross join) of all the sources. But usually qualification conditions
238 are added (via WHERE) to restrict the returned rows to a small subset
239 of the Cartesian product.
241 The FROM clause can contain the following elements:
244 The name (optionally schema-qualified) of an existing table or
245 view. If ONLY is specified before the table name, only that
246 table is scanned. If ONLY is not specified, the table and all
247 its descendant tables (if any) are scanned. Optionally, * can be
248 specified after the table name to explicitly indicate that
249 descendant tables are included.
252 A substitute name for the FROM item containing the alias. An
253 alias is used for brevity or to eliminate ambiguity for
254 self-joins (where the same table is scanned multiple times).
255 When an alias is provided, it completely hides the actual name
256 of the table or function; for example given FROM foo AS f, the
257 remainder of the SELECT must refer to this FROM item as f not
258 foo. If an alias is written, a column alias list can also be
259 written to provide substitute names for one or more columns of
262 TABLESAMPLE sampling_method ( argument [, ...] ) [ REPEATABLE ( seed )
264 A TABLESAMPLE clause after a table_name indicates that the
265 specified sampling_method should be used to retrieve a subset of
266 the rows in that table. This sampling precedes the application
267 of any other filters such as WHERE clauses. The standard
268 PostgreSQL distribution includes two sampling methods, BERNOULLI
269 and SYSTEM, and other sampling methods can be installed in the
270 database via extensions.
272 The BERNOULLI and SYSTEM sampling methods each accept a single
273 argument which is the fraction of the table to sample, expressed
274 as a percentage between 0 and 100. This argument can be any
275 real-valued expression. (Other sampling methods might accept
276 more or different arguments.) These two methods each return a
277 randomly-chosen sample of the table that will contain
278 approximately the specified percentage of the table's rows. The
279 BERNOULLI method scans the whole table and selects or ignores
280 individual rows independently with the specified probability.
281 The SYSTEM method does block-level sampling with each block
282 having the specified chance of being selected; all rows in each
283 selected block are returned. The SYSTEM method is significantly
284 faster than the BERNOULLI method when small sampling percentages
285 are specified, but it may return a less-random sample of the
286 table as a result of clustering effects.
288 The optional REPEATABLE clause specifies a seed number or
289 expression to use for generating random numbers within the
290 sampling method. The seed value can be any non-null
291 floating-point value. Two queries that specify the same seed and
292 argument values will select the same sample of the table, if the
293 table has not been changed meanwhile. But different seed values
294 will usually produce different samples. If REPEATABLE is not
295 given then a new random sample is selected for each query, based
296 upon a system-generated seed. Note that some add-on sampling
297 methods do not accept REPEATABLE, and will always produce new
301 A sub-SELECT can appear in the FROM clause. This acts as though
302 its output were created as a temporary table for the duration of
303 this single SELECT command. Note that the sub-SELECT must be
304 surrounded by parentheses, and an alias can be provided in the
305 same way as for a table. A VALUES command can also be used here.
308 A WITH query is referenced by writing its name, just as though
309 the query's name were a table name. (In fact, the WITH query
310 hides any real table of the same name for the purposes of the
311 primary query. If necessary, you can refer to a real table of
312 the same name by schema-qualifying the table's name.) An alias
313 can be provided in the same way as for a table.
316 Function calls can appear in the FROM clause. (This is
317 especially useful for functions that return result sets, but any
318 function can be used.) This acts as though the function's output
319 were created as a temporary table for the duration of this
320 single SELECT command. If the function's result type is
321 composite (including the case of a function with multiple OUT
322 parameters), each attribute becomes a separate column in the
325 When the optional WITH ORDINALITY clause is added to the
326 function call, an additional column of type bigint will be
327 appended to the function's result column(s). This column numbers
328 the rows of the function's result set, starting from 1. By
329 default, this column is named ordinality.
331 An alias can be provided in the same way as for a table. If an
332 alias is written, a column alias list can also be written to
333 provide substitute names for one or more attributes of the
334 function's composite return type, including the ordinality
337 Multiple function calls can be combined into a single
338 FROM-clause item by surrounding them with ROWS FROM( ... ). The
339 output of such an item is the concatenation of the first row
340 from each function, then the second row from each function, etc.
341 If some of the functions produce fewer rows than others, null
342 values are substituted for the missing data, so that the total
343 number of rows returned is always the same as for the function
344 that produced the most rows.
346 If the function has been defined as returning the record data
347 type, then an alias or the key word AS must be present, followed
348 by a column definition list in the form ( column_name data_type
349 [, ... ]). The column definition list must match the actual
350 number and types of columns returned by the function.
352 When using the ROWS FROM( ... ) syntax, if one of the functions
353 requires a column definition list, it's preferred to put the
354 column definition list after the function call inside ROWS FROM(
355 ... ). A column definition list can be placed after the ROWS
356 FROM( ... ) construct only if there's just a single function and
357 no WITH ORDINALITY clause.
359 To use ORDINALITY together with a column definition list, you
360 must use the ROWS FROM( ... ) syntax and put the column
361 definition list inside ROWS FROM( ... ).
367 + LEFT [ OUTER ] JOIN
368 + RIGHT [ OUTER ] JOIN
369 + FULL [ OUTER ] JOIN
371 For the INNER and OUTER join types, a join condition must be
372 specified, namely exactly one of ON join_condition, USING
373 (join_column [, ...]), or NATURAL. See below for the meaning.
375 A JOIN clause combines two FROM items, which for convenience we
376 will refer to as “tables”, though in reality they can be any
377 type of FROM item. Use parentheses if necessary to determine the
378 order of nesting. In the absence of parentheses, JOINs nest
379 left-to-right. In any case JOIN binds more tightly than the
380 commas separating FROM-list items. All the JOIN options are just
381 a notational convenience, since they do nothing you couldn't do
382 with plain FROM and WHERE.
384 LEFT OUTER JOIN returns all rows in the qualified Cartesian
385 product (i.e., all combined rows that pass its join condition),
386 plus one copy of each row in the left-hand table for which there
387 was no right-hand row that passed the join condition. This
388 left-hand row is extended to the full width of the joined table
389 by inserting null values for the right-hand columns. Note that
390 only the JOIN clause's own condition is considered while
391 deciding which rows have matches. Outer conditions are applied
394 Conversely, RIGHT OUTER JOIN returns all the joined rows, plus
395 one row for each unmatched right-hand row (extended with nulls
396 on the left). This is just a notational convenience, since you
397 could convert it to a LEFT OUTER JOIN by switching the left and
400 FULL OUTER JOIN returns all the joined rows, plus one row for
401 each unmatched left-hand row (extended with nulls on the right),
402 plus one row for each unmatched right-hand row (extended with
406 join_condition is an expression resulting in a value of type
407 boolean (similar to a WHERE clause) that specifies which rows in
408 a join are considered to match.
410 USING ( join_column [, ...] ) [ AS join_using_alias ]
411 A clause of the form USING ( a, b, ... ) is shorthand for ON
412 left_table.a = right_table.a AND left_table.b = right_table.b
413 .... Also, USING implies that only one of each pair of
414 equivalent columns will be included in the join output, not
417 If a join_using_alias name is specified, it provides a table
418 alias for the join columns. Only the join columns listed in the
419 USING clause are addressable by this name. Unlike a regular
420 alias, this does not hide the names of the joined tables from
421 the rest of the query. Also unlike a regular alias, you cannot
422 write a column alias list — the output names of the join columns
423 are the same as they appear in the USING list.
426 NATURAL is shorthand for a USING list that mentions all columns
427 in the two tables that have matching names. If there are no
428 common column names, NATURAL is equivalent to ON TRUE.
431 CROSS JOIN is equivalent to INNER JOIN ON (TRUE), that is, no
432 rows are removed by qualification. They produce a simple
433 Cartesian product, the same result as you get from listing the
434 two tables at the top level of FROM, but restricted by the join
438 The LATERAL key word can precede a sub-SELECT FROM item. This
439 allows the sub-SELECT to refer to columns of FROM items that
440 appear before it in the FROM list. (Without LATERAL, each
441 sub-SELECT is evaluated independently and so cannot
442 cross-reference any other FROM item.)
444 LATERAL can also precede a function-call FROM item, but in this
445 case it is a noise word, because the function expression can
446 refer to earlier FROM items in any case.
448 A LATERAL item can appear at top level in the FROM list, or
449 within a JOIN tree. In the latter case it can also refer to any
450 items that are on the left-hand side of a JOIN that it is on the
453 When a FROM item contains LATERAL cross-references, evaluation
454 proceeds as follows: for each row of the FROM item providing the
455 cross-referenced column(s), or set of rows of multiple FROM
456 items providing the columns, the LATERAL item is evaluated using
457 that row or row set's values of the columns. The resulting
458 row(s) are joined as usual with the rows they were computed
459 from. This is repeated for each row or set of rows from the
460 column source table(s).
462 The column source table(s) must be INNER or LEFT joined to the
463 LATERAL item, else there would not be a well-defined set of rows
464 from which to compute each set of rows for the LATERAL item.
465 Thus, although a construct such as X RIGHT JOIN LATERAL Y is
466 syntactically valid, it is not actually allowed for Y to
471 The optional WHERE clause has the general form
474 where condition is any expression that evaluates to a result of type
475 boolean. Any row that does not satisfy this condition will be
476 eliminated from the output. A row satisfies the condition if it returns
477 true when the actual row values are substituted for any variable
482 The optional GROUP BY clause has the general form
483 GROUP BY [ ALL | DISTINCT ] grouping_element [, ...]
485 GROUP BY will condense into a single row all selected rows that share
486 the same values for the grouped expressions. An expression used inside
487 a grouping_element can be an input column name, or the name or ordinal
488 number of an output column (SELECT list item), or an arbitrary
489 expression formed from input-column values. In case of ambiguity, a
490 GROUP BY name will be interpreted as an input-column name rather than
491 an output column name.
493 If any of GROUPING SETS, ROLLUP or CUBE are present as grouping
494 elements, then the GROUP BY clause as a whole defines some number of
495 independent grouping sets. The effect of this is equivalent to
496 constructing a UNION ALL between subqueries with the individual
497 grouping sets as their GROUP BY clauses. The optional DISTINCT clause
498 removes duplicate sets before processing; it does not transform the
499 UNION ALL into a UNION DISTINCT. For further details on the handling of
500 grouping sets see Section 7.2.4.
502 Aggregate functions, if any are used, are computed across all rows
503 making up each group, producing a separate value for each group. (If
504 there are aggregate functions but no GROUP BY clause, the query is
505 treated as having a single group comprising all the selected rows.) The
506 set of rows fed to each aggregate function can be further filtered by
507 attaching a FILTER clause to the aggregate function call; see
508 Section 4.2.7 for more information. When a FILTER clause is present,
509 only those rows matching it are included in the input to that aggregate
512 When GROUP BY is present, or any aggregate functions are present, it is
513 not valid for the SELECT list expressions to refer to ungrouped columns
514 except within aggregate functions or when the ungrouped column is
515 functionally dependent on the grouped columns, since there would
516 otherwise be more than one possible value to return for an ungrouped
517 column. A functional dependency exists if the grouped columns (or a
518 subset thereof) are the primary key of the table containing the
521 Keep in mind that all aggregate functions are evaluated before
522 evaluating any “scalar” expressions in the HAVING clause or SELECT
523 list. This means that, for example, a CASE expression cannot be used to
524 skip evaluation of an aggregate function; see Section 4.2.14.
526 Currently, FOR NO KEY UPDATE, FOR UPDATE, FOR SHARE and FOR KEY SHARE
527 cannot be specified with GROUP BY.
531 The optional HAVING clause has the general form
534 where condition is the same as specified for the WHERE clause.
536 HAVING eliminates group rows that do not satisfy the condition. HAVING
537 is different from WHERE: WHERE filters individual rows before the
538 application of GROUP BY, while HAVING filters group rows created by
539 GROUP BY. Each column referenced in condition must unambiguously
540 reference a grouping column, unless the reference appears within an
541 aggregate function or the ungrouped column is functionally dependent on
542 the grouping columns.
544 The presence of HAVING turns a query into a grouped query even if there
545 is no GROUP BY clause. This is the same as what happens when the query
546 contains aggregate functions but no GROUP BY clause. All the selected
547 rows are considered to form a single group, and the SELECT list and
548 HAVING clause can only reference table columns from within aggregate
549 functions. Such a query will emit a single row if the HAVING condition
550 is true, zero rows if it is not true.
552 Currently, FOR NO KEY UPDATE, FOR UPDATE, FOR SHARE and FOR KEY SHARE
553 cannot be specified with HAVING.
557 The optional WINDOW clause has the general form
558 WINDOW window_name AS ( window_definition ) [, ...]
560 where window_name is a name that can be referenced from OVER clauses or
561 subsequent window definitions, and window_definition is
562 [ existing_window_name ]
563 [ PARTITION BY expression [, ...] ]
564 [ ORDER BY expression [ ASC | DESC | USING operator ] [ NULLS { FIRST | LAST } ]
568 If an existing_window_name is specified it must refer to an earlier
569 entry in the WINDOW list; the new window copies its partitioning clause
570 from that entry, as well as its ordering clause if any. In this case
571 the new window cannot specify its own PARTITION BY clause, and it can
572 specify ORDER BY only if the copied window does not have one. The new
573 window always uses its own frame clause; the copied window must not
574 specify a frame clause.
576 The elements of the PARTITION BY list are interpreted in much the same
577 fashion as elements of a GROUP BY clause, except that they are always
578 simple expressions and never the name or number of an output column.
579 Another difference is that these expressions can contain aggregate
580 function calls, which are not allowed in a regular GROUP BY clause.
581 They are allowed here because windowing occurs after grouping and
584 Similarly, the elements of the ORDER BY list are interpreted in much
585 the same fashion as elements of a statement-level ORDER BY clause,
586 except that the expressions are always taken as simple expressions and
587 never the name or number of an output column.
589 The optional frame_clause defines the window frame for window functions
590 that depend on the frame (not all do). The window frame is a set of
591 related rows for each row of the query (called the current row). The
592 frame_clause can be one of
593 { RANGE | ROWS | GROUPS } frame_start [ frame_exclusion ]
594 { RANGE | ROWS | GROUPS } BETWEEN frame_start AND frame_end [ frame_exclusion ]
596 where frame_start and frame_end can be one of
603 and frame_exclusion can be one of
609 If frame_end is omitted it defaults to CURRENT ROW. Restrictions are
610 that frame_start cannot be UNBOUNDED FOLLOWING, frame_end cannot be
611 UNBOUNDED PRECEDING, and the frame_end choice cannot appear earlier in
612 the above list of frame_start and frame_end options than the
613 frame_start choice does — for example RANGE BETWEEN CURRENT ROW AND
614 offset PRECEDING is not allowed.
616 The default framing option is RANGE UNBOUNDED PRECEDING, which is the
617 same as RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW; it sets the
618 frame to be all rows from the partition start up through the current
619 row's last peer (a row that the window's ORDER BY clause considers
620 equivalent to the current row; all rows are peers if there is no ORDER
621 BY). In general, UNBOUNDED PRECEDING means that the frame starts with
622 the first row of the partition, and similarly UNBOUNDED FOLLOWING means
623 that the frame ends with the last row of the partition, regardless of
624 RANGE, ROWS or GROUPS mode. In ROWS mode, CURRENT ROW means that the
625 frame starts or ends with the current row; but in RANGE or GROUPS mode
626 it means that the frame starts or ends with the current row's first or
627 last peer in the ORDER BY ordering. The offset PRECEDING and offset
628 FOLLOWING options vary in meaning depending on the frame mode. In ROWS
629 mode, the offset is an integer indicating that the frame starts or ends
630 that many rows before or after the current row. In GROUPS mode, the
631 offset is an integer indicating that the frame starts or ends that many
632 peer groups before or after the current row's peer group, where a peer
633 group is a group of rows that are equivalent according to the window's
634 ORDER BY clause. In RANGE mode, use of an offset option requires that
635 there be exactly one ORDER BY column in the window definition. Then the
636 frame contains those rows whose ordering column value is no more than
637 offset less than (for PRECEDING) or more than (for FOLLOWING) the
638 current row's ordering column value. In these cases the data type of
639 the offset expression depends on the data type of the ordering column.
640 For numeric ordering columns it is typically of the same type as the
641 ordering column, but for datetime ordering columns it is an interval.
642 In all these cases, the value of the offset must be non-null and
643 non-negative. Also, while the offset does not have to be a simple
644 constant, it cannot contain variables, aggregate functions, or window
647 The frame_exclusion option allows rows around the current row to be
648 excluded from the frame, even if they would be included according to
649 the frame start and frame end options. EXCLUDE CURRENT ROW excludes the
650 current row from the frame. EXCLUDE GROUP excludes the current row and
651 its ordering peers from the frame. EXCLUDE TIES excludes any peers of
652 the current row from the frame, but not the current row itself. EXCLUDE
653 NO OTHERS simply specifies explicitly the default behavior of not
654 excluding the current row or its peers.
656 Beware that the ROWS mode can produce unpredictable results if the
657 ORDER BY ordering does not order the rows uniquely. The RANGE and
658 GROUPS modes are designed to ensure that rows that are peers in the
659 ORDER BY ordering are treated alike: all rows of a given peer group
660 will be in the frame or excluded from it.
662 The purpose of a WINDOW clause is to specify the behavior of window
663 functions appearing in the query's SELECT list or ORDER BY clause.
664 These functions can reference the WINDOW clause entries by name in
665 their OVER clauses. A WINDOW clause entry does not have to be
666 referenced anywhere, however; if it is not used in the query it is
667 simply ignored. It is possible to use window functions without any
668 WINDOW clause at all, since a window function call can specify its
669 window definition directly in its OVER clause. However, the WINDOW
670 clause saves typing when the same window definition is needed for more
671 than one window function.
673 Currently, FOR NO KEY UPDATE, FOR UPDATE, FOR SHARE and FOR KEY SHARE
674 cannot be specified with WINDOW.
676 Window functions are described in detail in Section 3.5, Section 4.2.8,
681 The SELECT list (between the key words SELECT and FROM) specifies
682 expressions that form the output rows of the SELECT statement. The
683 expressions can (and usually do) refer to columns computed in the FROM
686 Just as in a table, every output column of a SELECT has a name. In a
687 simple SELECT this name is just used to label the column for display,
688 but when the SELECT is a sub-query of a larger query, the name is seen
689 by the larger query as the column name of the virtual table produced by
690 the sub-query. To specify the name to use for an output column, write
691 AS output_name after the column's expression. (You can omit AS, but
692 only if the desired output name does not match any PostgreSQL keyword
693 (see Appendix C). For protection against possible future keyword
694 additions, it is recommended that you always either write AS or
695 double-quote the output name.) If you do not specify a column name, a
696 name is chosen automatically by PostgreSQL. If the column's expression
697 is a simple column reference then the chosen name is the same as that
698 column's name. In more complex cases a function or type name may be
699 used, or the system may fall back on a generated name such as ?column?.
701 An output column's name can be used to refer to the column's value in
702 ORDER BY and GROUP BY clauses, but not in the WHERE or HAVING clauses;
703 there you must write out the expression instead.
705 Instead of an expression, * can be written in the output list as a
706 shorthand for all the columns of the selected rows. Also, you can write
707 table_name.* as a shorthand for the columns coming from just that
708 table. In these cases it is not possible to specify new names with AS;
709 the output column names will be the same as the table columns' names.
711 According to the SQL standard, the expressions in the output list
712 should be computed before applying DISTINCT, ORDER BY, or LIMIT. This
713 is obviously necessary when using DISTINCT, since otherwise it's not
714 clear what values are being made distinct. However, in many cases it is
715 convenient if output expressions are computed after ORDER BY and LIMIT;
716 particularly if the output list contains any volatile or expensive
717 functions. With that behavior, the order of function evaluations is
718 more intuitive and there will not be evaluations corresponding to rows
719 that never appear in the output. PostgreSQL will effectively evaluate
720 output expressions after sorting and limiting, so long as those
721 expressions are not referenced in DISTINCT, ORDER BY or GROUP BY. (As a
722 counterexample, SELECT f(x) FROM tab ORDER BY 1 clearly must evaluate
723 f(x) before sorting.) Output expressions that contain set-returning
724 functions are effectively evaluated after sorting and before limiting,
725 so that LIMIT will act to cut off the output from a set-returning
730 PostgreSQL versions before 9.6 did not provide any guarantees about the
731 timing of evaluation of output expressions versus sorting and limiting;
732 it depended on the form of the chosen query plan.
736 If SELECT DISTINCT is specified, all duplicate rows are removed from
737 the result set (one row is kept from each group of duplicates). SELECT
738 ALL specifies the opposite: all rows are kept; that is the default.
740 SELECT DISTINCT ON ( expression [, ...] ) keeps only the first row of
741 each set of rows where the given expressions evaluate to equal. The
742 DISTINCT ON expressions are interpreted using the same rules as for
743 ORDER BY (see above). Note that the “first row” of each set is
744 unpredictable unless ORDER BY is used to ensure that the desired row
745 appears first. For example:
746 SELECT DISTINCT ON (location) location, time, report
748 ORDER BY location, time DESC;
750 retrieves the most recent weather report for each location. But if we
751 had not used ORDER BY to force descending order of time values for each
752 location, we'd have gotten a report from an unpredictable time for each
755 The DISTINCT ON expression(s) must match the leftmost ORDER BY
756 expression(s). The ORDER BY clause will normally contain additional
757 expression(s) that determine the desired precedence of rows within each
760 Currently, FOR NO KEY UPDATE, FOR UPDATE, FOR SHARE and FOR KEY SHARE
761 cannot be specified with DISTINCT.
765 The UNION clause has this general form:
766 select_statement UNION [ ALL | DISTINCT ] select_statement
768 select_statement is any SELECT statement without an ORDER BY, LIMIT,
769 FOR NO KEY UPDATE, FOR UPDATE, FOR SHARE, or FOR KEY SHARE clause.
770 (ORDER BY and LIMIT can be attached to a subexpression if it is
771 enclosed in parentheses. Without parentheses, these clauses will be
772 taken to apply to the result of the UNION, not to its right-hand input
775 The UNION operator computes the set union of the rows returned by the
776 involved SELECT statements. A row is in the set union of two result
777 sets if it appears in at least one of the result sets. The two SELECT
778 statements that represent the direct operands of the UNION must produce
779 the same number of columns, and corresponding columns must be of
780 compatible data types.
782 The result of UNION does not contain any duplicate rows unless the ALL
783 option is specified. ALL prevents elimination of duplicates.
784 (Therefore, UNION ALL is usually significantly quicker than UNION; use
785 ALL when you can.) DISTINCT can be written to explicitly specify the
786 default behavior of eliminating duplicate rows.
788 Multiple UNION operators in the same SELECT statement are evaluated
789 left to right, unless otherwise indicated by parentheses.
791 Currently, FOR NO KEY UPDATE, FOR UPDATE, FOR SHARE and FOR KEY SHARE
792 cannot be specified either for a UNION result or for any input of a
797 The INTERSECT clause has this general form:
798 select_statement INTERSECT [ ALL | DISTINCT ] select_statement
800 select_statement is any SELECT statement without an ORDER BY, LIMIT,
801 FOR NO KEY UPDATE, FOR UPDATE, FOR SHARE, or FOR KEY SHARE clause.
803 The INTERSECT operator computes the set intersection of the rows
804 returned by the involved SELECT statements. A row is in the
805 intersection of two result sets if it appears in both result sets.
807 The result of INTERSECT does not contain any duplicate rows unless the
808 ALL option is specified. With ALL, a row that has m duplicates in the
809 left table and n duplicates in the right table will appear min(m,n)
810 times in the result set. DISTINCT can be written to explicitly specify
811 the default behavior of eliminating duplicate rows.
813 Multiple INTERSECT operators in the same SELECT statement are evaluated
814 left to right, unless parentheses dictate otherwise. INTERSECT binds
815 more tightly than UNION. That is, A UNION B INTERSECT C will be read as
816 A UNION (B INTERSECT C).
818 Currently, FOR NO KEY UPDATE, FOR UPDATE, FOR SHARE and FOR KEY SHARE
819 cannot be specified either for an INTERSECT result or for any input of
824 The EXCEPT clause has this general form:
825 select_statement EXCEPT [ ALL | DISTINCT ] select_statement
827 select_statement is any SELECT statement without an ORDER BY, LIMIT,
828 FOR NO KEY UPDATE, FOR UPDATE, FOR SHARE, or FOR KEY SHARE clause.
830 The EXCEPT operator computes the set of rows that are in the result of
831 the left SELECT statement but not in the result of the right one.
833 The result of EXCEPT does not contain any duplicate rows unless the ALL
834 option is specified. With ALL, a row that has m duplicates in the left
835 table and n duplicates in the right table will appear max(m-n,0) times
836 in the result set. DISTINCT can be written to explicitly specify the
837 default behavior of eliminating duplicate rows.
839 Multiple EXCEPT operators in the same SELECT statement are evaluated
840 left to right, unless parentheses dictate otherwise. EXCEPT binds at
841 the same level as UNION.
843 Currently, FOR NO KEY UPDATE, FOR UPDATE, FOR SHARE and FOR KEY SHARE
844 cannot be specified either for an EXCEPT result or for any input of an
849 The optional ORDER BY clause has this general form:
850 ORDER BY expression [ ASC | DESC | USING operator ] [ NULLS { FIRST | LAST } ] [
853 The ORDER BY clause causes the result rows to be sorted according to
854 the specified expression(s). If two rows are equal according to the
855 leftmost expression, they are compared according to the next expression
856 and so on. If they are equal according to all specified expressions,
857 they are returned in an implementation-dependent order.
859 Each expression can be the name or ordinal number of an output column
860 (SELECT list item), or it can be an arbitrary expression formed from
863 The ordinal number refers to the ordinal (left-to-right) position of
864 the output column. This feature makes it possible to define an ordering
865 on the basis of a column that does not have a unique name. This is
866 never absolutely necessary because it is always possible to assign a
867 name to an output column using the AS clause.
869 It is also possible to use arbitrary expressions in the ORDER BY
870 clause, including columns that do not appear in the SELECT output list.
871 Thus the following statement is valid:
872 SELECT name FROM distributors ORDER BY code;
874 A limitation of this feature is that an ORDER BY clause applying to the
875 result of a UNION, INTERSECT, or EXCEPT clause can only specify an
876 output column name or number, not an expression.
878 If an ORDER BY expression is a simple name that matches both an output
879 column name and an input column name, ORDER BY will interpret it as the
880 output column name. This is the opposite of the choice that GROUP BY
881 will make in the same situation. This inconsistency is made to be
882 compatible with the SQL standard.
884 Optionally one can add the key word ASC (ascending) or DESC
885 (descending) after any expression in the ORDER BY clause. If not
886 specified, ASC is assumed by default. Alternatively, a specific
887 ordering operator name can be specified in the USING clause. An
888 ordering operator must be a less-than or greater-than member of some
889 B-tree operator family. ASC is usually equivalent to USING < and DESC
890 is usually equivalent to USING >. (But the creator of a user-defined
891 data type can define exactly what the default sort ordering is, and it
892 might correspond to operators with other names.)
894 If NULLS LAST is specified, null values sort after all non-null values;
895 if NULLS FIRST is specified, null values sort before all non-null
896 values. If neither is specified, the default behavior is NULLS LAST
897 when ASC is specified or implied, and NULLS FIRST when DESC is
898 specified (thus, the default is to act as though nulls are larger than
899 non-nulls). When USING is specified, the default nulls ordering depends
900 on whether the operator is a less-than or greater-than operator.
902 Note that ordering options apply only to the expression they follow;
903 for example ORDER BY x, y DESC does not mean the same thing as ORDER BY
906 Character-string data is sorted according to the collation that applies
907 to the column being sorted. That can be overridden at need by including
908 a COLLATE clause in the expression, for example ORDER BY mycolumn
909 COLLATE "en_US". For more information see Section 4.2.10 and
914 The LIMIT clause consists of two independent sub-clauses:
915 LIMIT { count | ALL }
918 The parameter count specifies the maximum number of rows to return,
919 while start specifies the number of rows to skip before starting to
920 return rows. When both are specified, start rows are skipped before
921 starting to count the count rows to be returned.
923 If the count expression evaluates to NULL, it is treated as LIMIT ALL,
924 i.e., no limit. If start evaluates to NULL, it is treated the same as
927 SQL:2008 introduced a different syntax to achieve the same result,
928 which PostgreSQL also supports. It is:
929 OFFSET start { ROW | ROWS }
930 FETCH { FIRST | NEXT } [ count ] { ROW | ROWS } { ONLY | WITH TIES }
932 In this syntax, the start or count value is required by the standard to
933 be a literal constant, a parameter, or a variable name; as a PostgreSQL
934 extension, other expressions are allowed, but will generally need to be
935 enclosed in parentheses to avoid ambiguity. If count is omitted in a
936 FETCH clause, it defaults to 1. The WITH TIES option is used to return
937 any additional rows that tie for the last place in the result set
938 according to the ORDER BY clause; ORDER BY is mandatory in this case,
939 and SKIP LOCKED is not allowed. ROW and ROWS as well as FIRST and NEXT
940 are noise words that don't influence the effects of these clauses.
941 According to the standard, the OFFSET clause must come before the FETCH
942 clause if both are present; but PostgreSQL is laxer and allows either
945 When using LIMIT, it is a good idea to use an ORDER BY clause that
946 constrains the result rows into a unique order. Otherwise you will get
947 an unpredictable subset of the query's rows — you might be asking for
948 the tenth through twentieth rows, but tenth through twentieth in what
949 ordering? You don't know what ordering unless you specify ORDER BY.
951 The query planner takes LIMIT into account when generating a query
952 plan, so you are very likely to get different plans (yielding different
953 row orders) depending on what you use for LIMIT and OFFSET. Thus, using
954 different LIMIT/OFFSET values to select different subsets of a query
955 result will give inconsistent results unless you enforce a predictable
956 result ordering with ORDER BY. This is not a bug; it is an inherent
957 consequence of the fact that SQL does not promise to deliver the
958 results of a query in any particular order unless ORDER BY is used to
961 It is even possible for repeated executions of the same LIMIT query to
962 return different subsets of the rows of a table, if there is not an
963 ORDER BY to enforce selection of a deterministic subset. Again, this is
964 not a bug; determinism of the results is simply not guaranteed in such
969 FOR UPDATE, FOR NO KEY UPDATE, FOR SHARE and FOR KEY SHARE are locking
970 clauses; they affect how SELECT locks rows as they are obtained from
973 The locking clause has the general form
974 FOR lock_strength [ OF from_reference [, ...] ] [ NOWAIT | SKIP LOCKED ]
976 where lock_strength can be one of
982 from_reference must be a table alias or non-hidden table_name
983 referenced in the FROM clause. For more information on each row-level
984 lock mode, refer to Section 13.3.2.
986 To prevent the operation from waiting for other transactions to commit,
987 use either the NOWAIT or SKIP LOCKED option. With NOWAIT, the statement
988 reports an error, rather than waiting, if a selected row cannot be
989 locked immediately. With SKIP LOCKED, any selected rows that cannot be
990 immediately locked are skipped. Skipping locked rows provides an
991 inconsistent view of the data, so this is not suitable for general
992 purpose work, but can be used to avoid lock contention with multiple
993 consumers accessing a queue-like table. Note that NOWAIT and SKIP
994 LOCKED apply only to the row-level lock(s) — the required ROW SHARE
995 table-level lock is still taken in the ordinary way (see Chapter 13).
996 You can use LOCK with the NOWAIT option first, if you need to acquire
997 the table-level lock without waiting.
999 If specific tables are named in a locking clause, then only rows coming
1000 from those tables are locked; any other tables used in the SELECT are
1001 simply read as usual. A locking clause without a table list affects all
1002 tables used in the statement. If a locking clause is applied to a view
1003 or sub-query, it affects all tables used in the view or sub-query.
1004 However, these clauses do not apply to WITH queries referenced by the
1005 primary query. If you want row locking to occur within a WITH query,
1006 specify a locking clause within the WITH query.
1008 Multiple locking clauses can be written if it is necessary to specify
1009 different locking behavior for different tables. If the same table is
1010 mentioned (or implicitly affected) by more than one locking clause,
1011 then it is processed as if it was only specified by the strongest one.
1012 Similarly, a table is processed as NOWAIT if that is specified in any
1013 of the clauses affecting it. Otherwise, it is processed as SKIP LOCKED
1014 if that is specified in any of the clauses affecting it.
1016 The locking clauses cannot be used in contexts where returned rows
1017 cannot be clearly identified with individual table rows; for example
1018 they cannot be used with aggregation.
1020 When a locking clause appears at the top level of a SELECT query, the
1021 rows that are locked are exactly those that are returned by the query;
1022 in the case of a join query, the rows locked are those that contribute
1023 to returned join rows. In addition, rows that satisfied the query
1024 conditions as of the query snapshot will be locked, although they will
1025 not be returned if they were updated after the snapshot and no longer
1026 satisfy the query conditions. If a LIMIT is used, locking stops once
1027 enough rows have been returned to satisfy the limit (but note that rows
1028 skipped over by OFFSET will get locked). Similarly, if a locking clause
1029 is used in a cursor's query, only rows actually fetched or stepped past
1030 by the cursor will be locked.
1032 When a locking clause appears in a sub-SELECT, the rows locked are
1033 those returned to the outer query by the sub-query. This might involve
1034 fewer rows than inspection of the sub-query alone would suggest, since
1035 conditions from the outer query might be used to optimize execution of
1036 the sub-query. For example,
1037 SELECT * FROM (SELECT * FROM mytable FOR UPDATE) ss WHERE col1 = 5;
1039 will lock only rows having col1 = 5, even though that condition is not
1040 textually within the sub-query.
1042 Previous releases failed to preserve a lock which is upgraded by a
1043 later savepoint. For example, this code:
1045 SELECT * FROM mytable WHERE key = 1 FOR UPDATE;
1047 UPDATE mytable SET ... WHERE key = 1;
1050 would fail to preserve the FOR UPDATE lock after the ROLLBACK TO. This
1051 has been fixed in release 9.3.
1055 It is possible for a SELECT command running at the READ COMMITTED
1056 transaction isolation level and using ORDER BY and a locking clause to
1057 return rows out of order. This is because ORDER BY is applied first.
1058 The command sorts the result, but might then block trying to obtain a
1059 lock on one or more of the rows. Once the SELECT unblocks, some of the
1060 ordering column values might have been modified, leading to those rows
1061 appearing to be out of order (though they are in order in terms of the
1062 original column values). This can be worked around at need by placing
1063 the FOR UPDATE/SHARE clause in a sub-query, for example
1064 SELECT * FROM (SELECT * FROM mytable FOR UPDATE) ss ORDER BY column1;
1066 Note that this will result in locking all rows of mytable, whereas FOR
1067 UPDATE at the top level would lock only the actually returned rows.
1068 This can make for a significant performance difference, particularly if
1069 the ORDER BY is combined with LIMIT or other restrictions. So this
1070 technique is recommended only if concurrent updates of the ordering
1071 columns are expected and a strictly sorted result is required.
1073 At the REPEATABLE READ or SERIALIZABLE transaction isolation level this
1074 would cause a serialization failure (with an SQLSTATE of '40001'), so
1075 there is no possibility of receiving rows out of order under these
1086 It can be used as a top-level command or as a space-saving syntax
1087 variant in parts of complex queries. Only the WITH, UNION, INTERSECT,
1088 EXCEPT, ORDER BY, LIMIT, OFFSET, FETCH and FOR locking clauses can be
1089 used with TABLE; the WHERE clause and any form of aggregation cannot be
1094 To join the table films with the table distributors:
1095 SELECT f.title, f.did, d.name, f.date_prod, f.kind
1096 FROM distributors d JOIN films f USING (did);
1098 title | did | name | date_prod | kind
1099 -------------------+-----+--------------+------------+----------
1100 The Third Man | 101 | British Lion | 1949-12-23 | Drama
1101 The African Queen | 101 | British Lion | 1951-08-11 | Romantic
1104 To sum the column len of all films and group the results by kind:
1105 SELECT kind, sum(len) AS total FROM films GROUP BY kind;
1115 To sum the column len of all films, group the results by kind and show
1116 those group totals that are less than 5 hours:
1117 SELECT kind, sum(len) AS total
1120 HAVING sum(len) < interval '5 hours';
1127 The following two examples are identical ways of sorting the individual
1128 results according to the contents of the second column (name):
1129 SELECT * FROM distributors ORDER BY name;
1130 SELECT * FROM distributors ORDER BY 2;
1133 -----+------------------
1134 109 | 20th Century Fox
1135 110 | Bavaria Atelier
1138 102 | Jean Luc Godard
1143 105 | United Artists
1148 The next example shows how to obtain the union of the tables
1149 distributors and actors, restricting the results to those that begin
1150 with the letter W in each table. Only distinct rows are wanted, so the
1151 key word ALL is omitted.
1152 distributors: actors:
1153 did | name id | name
1154 -----+-------------- ----+----------------
1155 108 | Westward 1 | Woody Allen
1156 111 | Walt Disney 2 | Warren Beatty
1157 112 | Warner Bros. 3 | Walter Matthau
1160 SELECT distributors.name
1162 WHERE distributors.name LIKE 'W%'
1166 WHERE actors.name LIKE 'W%';
1177 This example shows how to use a function in the FROM clause, both with
1178 and without a column definition list:
1179 CREATE FUNCTION distributors(int) RETURNS SETOF distributors AS $$
1180 SELECT * FROM distributors WHERE did = $1;
1183 SELECT * FROM distributors(111);
1188 CREATE FUNCTION distributors_2(int) RETURNS SETOF record AS $$
1189 SELECT * FROM distributors WHERE did = $1;
1192 SELECT * FROM distributors_2(111) AS (f1 int, f2 text);
1197 Here is an example of a function with an ordinality column added:
1198 SELECT * FROM unnest(ARRAY['a','b','c','d','e','f']) WITH ORDINALITY;
1209 This example shows how to use a simple WITH clause:
1211 SELECT random() as x FROM generate_series(1, 3)
1217 --------------------
1225 Notice that the WITH query was evaluated only once, so that we got two
1226 sets of the same three random values.
1228 This example uses WITH RECURSIVE to find all subordinates (direct or
1229 indirect) of the employee Mary, and their level of indirectness, from a
1230 table that shows only direct subordinates:
1231 WITH RECURSIVE employee_recursive(distance, employee_name, manager_name) AS (
1232 SELECT 1, employee_name, manager_name
1234 WHERE manager_name = 'Mary'
1236 SELECT er.distance + 1, e.employee_name, e.manager_name
1237 FROM employee_recursive er, employee e
1238 WHERE er.employee_name = e.manager_name
1240 SELECT distance, employee_name FROM employee_recursive;
1242 Notice the typical form of recursive queries: an initial condition,
1243 followed by UNION, followed by the recursive part of the query. Be sure
1244 that the recursive part of the query will eventually return no tuples,
1245 or else the query will loop indefinitely. (See Section 7.8 for more
1248 This example uses LATERAL to apply a set-returning function
1249 get_product_names() for each row of the manufacturers table:
1250 SELECT m.name AS mname, pname
1251 FROM manufacturers m, LATERAL get_product_names(m.id) pname;
1253 Manufacturers not currently having any products would not appear in the
1254 result, since it is an inner join. If we wished to include the names of
1255 such manufacturers in the result, we could do:
1256 SELECT m.name AS mname, pname
1257 FROM manufacturers m LEFT JOIN LATERAL get_product_names(m.id) pname ON true;
1261 Of course, the SELECT statement is compatible with the SQL standard.
1262 But there are some extensions and some missing features.
1264 Omitted FROM Clauses
1266 PostgreSQL allows one to omit the FROM clause. It has a straightforward
1267 use to compute the results of simple expressions:
1274 Some other SQL databases cannot do this except by introducing a dummy
1275 one-row table from which to do the SELECT.
1279 The list of output expressions after SELECT can be empty, producing a
1280 zero-column result table. This is not valid syntax according to the SQL
1281 standard. PostgreSQL allows it to be consistent with allowing
1282 zero-column tables. However, an empty list is not allowed when DISTINCT
1285 Omitting the AS Key Word
1287 In the SQL standard, the optional key word AS can be omitted before an
1288 output column name whenever the new column name is a valid column name
1289 (that is, not the same as any reserved keyword). PostgreSQL is slightly
1290 more restrictive: AS is required if the new column name matches any
1291 keyword at all, reserved or not. Recommended practice is to use AS or
1292 double-quote output column names, to prevent any possible conflict
1293 against future keyword additions.
1295 In FROM items, both the standard and PostgreSQL allow AS to be omitted
1296 before an alias that is an unreserved keyword. But this is impractical
1297 for output column names, because of syntactic ambiguities.
1299 Omitting Sub-SELECT Aliases in FROM
1301 According to the SQL standard, a sub-SELECT in the FROM list must have
1302 an alias. In PostgreSQL, this alias may be omitted.
1304 ONLY and Inheritance
1306 The SQL standard requires parentheses around the table name when
1307 writing ONLY, for example SELECT * FROM ONLY (tab1), ONLY (tab2) WHERE
1308 .... PostgreSQL considers these parentheses to be optional.
1310 PostgreSQL allows a trailing * to be written to explicitly specify the
1311 non-ONLY behavior of including child tables. The standard does not
1314 (These points apply equally to all SQL commands supporting the ONLY
1317 TABLESAMPLE Clause Restrictions
1319 The TABLESAMPLE clause is currently accepted only on regular tables and
1320 materialized views. According to the SQL standard it should be possible
1321 to apply it to any FROM item.
1323 Function Calls in FROM
1325 PostgreSQL allows a function call to be written directly as a member of
1326 the FROM list. In the SQL standard it would be necessary to wrap such a
1327 function call in a sub-SELECT; that is, the syntax FROM func(...) alias
1328 is approximately equivalent to FROM LATERAL (SELECT func(...)) alias.
1329 Note that LATERAL is considered to be implicit; this is because the
1330 standard requires LATERAL semantics for an UNNEST() item in FROM.
1331 PostgreSQL treats UNNEST() the same as other set-returning functions.
1333 Namespace Available to GROUP BY and ORDER BY
1335 In the SQL-92 standard, an ORDER BY clause can only use output column
1336 names or numbers, while a GROUP BY clause can only use expressions
1337 based on input column names. PostgreSQL extends each of these clauses
1338 to allow the other choice as well (but it uses the standard's
1339 interpretation if there is ambiguity). PostgreSQL also allows both
1340 clauses to specify arbitrary expressions. Note that names appearing in
1341 an expression will always be taken as input-column names, not as
1342 output-column names.
1344 SQL:1999 and later use a slightly different definition which is not
1345 entirely upward compatible with SQL-92. In most cases, however,
1346 PostgreSQL will interpret an ORDER BY or GROUP BY expression the same
1349 Functional Dependencies
1351 PostgreSQL recognizes functional dependency (allowing columns to be
1352 omitted from GROUP BY) only when a table's primary key is included in
1353 the GROUP BY list. The SQL standard specifies additional conditions
1354 that should be recognized.
1358 The clauses LIMIT and OFFSET are PostgreSQL-specific syntax, also used
1359 by MySQL. The SQL:2008 standard has introduced the clauses OFFSET ...
1360 FETCH {FIRST|NEXT} ... for the same functionality, as shown above in
1361 LIMIT Clause. This syntax is also used by IBM DB2. (Applications
1362 written for Oracle frequently use a workaround involving the
1363 automatically generated rownum column, which is not available in
1364 PostgreSQL, to implement the effects of these clauses.)
1366 FOR NO KEY UPDATE, FOR UPDATE, FOR SHARE, FOR KEY SHARE
1368 Although FOR UPDATE appears in the SQL standard, the standard allows it
1369 only as an option of DECLARE CURSOR. PostgreSQL allows it in any SELECT
1370 query as well as in sub-SELECTs, but this is an extension. The FOR NO
1371 KEY UPDATE, FOR SHARE and FOR KEY SHARE variants, as well as the NOWAIT
1372 and SKIP LOCKED options, do not appear in the standard.
1374 Data-Modifying Statements in WITH
1376 PostgreSQL allows INSERT, UPDATE, DELETE, and MERGE to be used as WITH
1377 queries. This is not found in the SQL standard.
1381 DISTINCT ON ( ... ) is an extension of the SQL standard.
1383 ROWS FROM( ... ) is an extension of the SQL standard.
1385 The MATERIALIZED and NOT MATERIALIZED options of WITH are extensions of