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