]> begriffs open source - ai-pg/blob - full-docs/man7/SELECT.7
Convert HTML docs to more streamlined TXT
[ai-pg] / full-docs / man7 / SELECT.7
1 '\" t
2 .\"     Title: SELECT
3 .\"    Author: The PostgreSQL Global Development Group
4 .\" Generator: DocBook XSL Stylesheets vsnapshot <http://docbook.sf.net/>
5 .\"      Date: 2025
6 .\"    Manual: PostgreSQL 18.0 Documentation
7 .\"    Source: PostgreSQL 18.0
8 .\"  Language: English
9 .\"
10 .TH "SELECT" "7" "2025" "PostgreSQL 18.0" "PostgreSQL 18.0 Documentation"
11 .\" -----------------------------------------------------------------
12 .\" * Define some portability stuff
13 .\" -----------------------------------------------------------------
14 .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
15 .\" http://bugs.debian.org/507673
16 .\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html
17 .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
18 .ie \n(.g .ds Aq \(aq
19 .el       .ds Aq '
20 .\" -----------------------------------------------------------------
21 .\" * set default formatting
22 .\" -----------------------------------------------------------------
23 .\" disable hyphenation
24 .nh
25 .\" disable justification (adjust text to left margin only)
26 .ad l
27 .\" -----------------------------------------------------------------
28 .\" * MAIN CONTENT STARTS HERE *
29 .\" -----------------------------------------------------------------
30 .SH "NAME"
31 SELECT, TABLE, WITH \- retrieve rows from a table or view
32 .SH "SYNOPSIS"
33 .sp
34 .nf
35 [ WITH [ RECURSIVE ] \fIwith_query\fR [, \&.\&.\&.] ]
36 SELECT [ ALL | DISTINCT [ ON ( \fIexpression\fR [, \&.\&.\&.] ) ] ]
37     [ { * | \fIexpression\fR [ [ AS ] \fIoutput_name\fR ] } [, \&.\&.\&.] ]
38     [ FROM \fIfrom_item\fR [, \&.\&.\&.] ]
39     [ WHERE \fIcondition\fR ]
40     [ GROUP BY [ ALL | DISTINCT ] \fIgrouping_element\fR [, \&.\&.\&.] ]
41     [ HAVING \fIcondition\fR ]
42     [ WINDOW \fIwindow_name\fR AS ( \fIwindow_definition\fR ) [, \&.\&.\&.] ]
43     [ { UNION | INTERSECT | EXCEPT } [ ALL | DISTINCT ] \fIselect\fR ]
44     [ ORDER BY \fIexpression\fR [ ASC | DESC | USING \fIoperator\fR ] [ NULLS { FIRST | LAST } ] [, \&.\&.\&.] ]
45     [ LIMIT { \fIcount\fR | ALL } ]
46     [ OFFSET \fIstart\fR [ ROW | ROWS ] ]
47     [ FETCH { FIRST | NEXT } [ \fIcount\fR ] { ROW | ROWS } { ONLY | WITH TIES } ]
48     [ FOR { UPDATE | NO KEY UPDATE | SHARE | KEY SHARE } [ OF \fIfrom_reference\fR [, \&.\&.\&.] ] [ NOWAIT | SKIP LOCKED ] [\&.\&.\&.] ]
49
50 where \fIfrom_item\fR can be one of:
51
52     [ ONLY ] \fItable_name\fR [ * ] [ [ AS ] \fIalias\fR [ ( \fIcolumn_alias\fR [, \&.\&.\&.] ) ] ]
53                 [ TABLESAMPLE \fIsampling_method\fR ( \fIargument\fR [, \&.\&.\&.] ) [ REPEATABLE ( \fIseed\fR ) ] ]
54     [ LATERAL ] ( \fIselect\fR ) [ [ AS ] \fIalias\fR [ ( \fIcolumn_alias\fR [, \&.\&.\&.] ) ] ]
55     \fIwith_query_name\fR [ [ AS ] \fIalias\fR [ ( \fIcolumn_alias\fR [, \&.\&.\&.] ) ] ]
56     [ LATERAL ] \fIfunction_name\fR ( [ \fIargument\fR [, \&.\&.\&.] ] )
57                 [ WITH ORDINALITY ] [ [ AS ] \fIalias\fR [ ( \fIcolumn_alias\fR [, \&.\&.\&.] ) ] ]
58     [ LATERAL ] \fIfunction_name\fR ( [ \fIargument\fR [, \&.\&.\&.] ] ) [ AS ] \fIalias\fR ( \fIcolumn_definition\fR [, \&.\&.\&.] )
59     [ LATERAL ] \fIfunction_name\fR ( [ \fIargument\fR [, \&.\&.\&.] ] ) AS ( \fIcolumn_definition\fR [, \&.\&.\&.] )
60     [ LATERAL ] ROWS FROM( \fIfunction_name\fR ( [ \fIargument\fR [, \&.\&.\&.] ] ) [ AS ( \fIcolumn_definition\fR [, \&.\&.\&.] ) ] [, \&.\&.\&.] )
61                 [ WITH ORDINALITY ] [ [ AS ] \fIalias\fR [ ( \fIcolumn_alias\fR [, \&.\&.\&.] ) ] ]
62     \fIfrom_item\fR \fIjoin_type\fR \fIfrom_item\fR { ON \fIjoin_condition\fR | USING ( \fIjoin_column\fR [, \&.\&.\&.] ) [ AS \fIjoin_using_alias\fR ] }
63     \fIfrom_item\fR NATURAL \fIjoin_type\fR \fIfrom_item\fR
64     \fIfrom_item\fR CROSS JOIN \fIfrom_item\fR
65
66 and \fIgrouping_element\fR can be one of:
67
68     ( )
69     \fIexpression\fR
70     ( \fIexpression\fR [, \&.\&.\&.] )
71     ROLLUP ( { \fIexpression\fR | ( \fIexpression\fR [, \&.\&.\&.] ) } [, \&.\&.\&.] )
72     CUBE ( { \fIexpression\fR | ( \fIexpression\fR [, \&.\&.\&.] ) } [, \&.\&.\&.] )
73     GROUPING SETS ( \fIgrouping_element\fR [, \&.\&.\&.] )
74
75 and \fIwith_query\fR is:
76
77     \fIwith_query_name\fR [ ( \fIcolumn_name\fR [, \&.\&.\&.] ) ] AS [ [ NOT ] MATERIALIZED ] ( \fIselect\fR | \fIvalues\fR | \fIinsert\fR | \fIupdate\fR | \fIdelete\fR | \fImerge\fR )
78         [ SEARCH { BREADTH | DEPTH } FIRST BY \fIcolumn_name\fR [, \&.\&.\&.] SET \fIsearch_seq_col_name\fR ]
79         [ CYCLE \fIcolumn_name\fR [, \&.\&.\&.] SET \fIcycle_mark_col_name\fR [ TO \fIcycle_mark_value\fR DEFAULT \fIcycle_mark_default\fR ] USING \fIcycle_path_col_name\fR ]
80
81 TABLE [ ONLY ] \fItable_name\fR [ * ]
82 .fi
83 .SH "DESCRIPTION"
84 .PP
85 \fBSELECT\fR
86 retrieves rows from zero or more tables\&. The general processing of
87 \fBSELECT\fR
88 is as follows:
89 .sp
90 .RS 4
91 .ie n \{\
92 \h'-04' 1.\h'+01'\c
93 .\}
94 .el \{\
95 .sp -1
96 .IP "  1." 4.2
97 .\}
98 All queries in the
99 WITH
100 list are computed\&. These effectively serve as temporary tables that can be referenced in the
101 FROM
102 list\&. A
103 WITH
104 query that is referenced more than once in
105 FROM
106 is computed only once, unless specified otherwise with
107 NOT MATERIALIZED\&. (See
108 WITH Clause
109 below\&.)
110 .RE
111 .sp
112 .RS 4
113 .ie n \{\
114 \h'-04' 2.\h'+01'\c
115 .\}
116 .el \{\
117 .sp -1
118 .IP "  2." 4.2
119 .\}
120 All elements in the
121 FROM
122 list are computed\&. (Each element in the
123 FROM
124 list is a real or virtual table\&.) If more than one element is specified in the
125 FROM
126 list, they are cross\-joined together\&. (See
127 FROM Clause
128 below\&.)
129 .RE
130 .sp
131 .RS 4
132 .ie n \{\
133 \h'-04' 3.\h'+01'\c
134 .\}
135 .el \{\
136 .sp -1
137 .IP "  3." 4.2
138 .\}
139 If the
140 WHERE
141 clause is specified, all rows that do not satisfy the condition are eliminated from the output\&. (See
142 WHERE Clause
143 below\&.)
144 .RE
145 .sp
146 .RS 4
147 .ie n \{\
148 \h'-04' 4.\h'+01'\c
149 .\}
150 .el \{\
151 .sp -1
152 .IP "  4." 4.2
153 .\}
154 If the
155 GROUP BY
156 clause is specified, or if there are aggregate function calls, the output is combined into groups of rows that match on one or more values, and the results of aggregate functions are computed\&. If the
157 HAVING
158 clause is present, it eliminates groups that do not satisfy the given condition\&. (See
159 GROUP BY Clause
160 and
161 HAVING Clause
162 below\&.) Although query output columns are nominally computed in the next step, they can also be referenced (by name or ordinal number) in the
163 GROUP BY
164 clause\&.
165 .RE
166 .sp
167 .RS 4
168 .ie n \{\
169 \h'-04' 5.\h'+01'\c
170 .\}
171 .el \{\
172 .sp -1
173 .IP "  5." 4.2
174 .\}
175 The actual output rows are computed using the
176 \fBSELECT\fR
177 output expressions for each selected row or row group\&. (See
178 SELECT List
179 below\&.)
180 .RE
181 .sp
182 .RS 4
183 .ie n \{\
184 \h'-04' 6.\h'+01'\c
185 .\}
186 .el \{\
187 .sp -1
188 .IP "  6." 4.2
189 .\}
190 SELECT DISTINCT
191 eliminates duplicate rows from the result\&.
192 SELECT DISTINCT ON
193 eliminates rows that match on all the specified expressions\&.
194 SELECT ALL
195 (the default) will return all candidate rows, including duplicates\&. (See
196 DISTINCT Clause
197 below\&.)
198 .RE
199 .sp
200 .RS 4
201 .ie n \{\
202 \h'-04' 7.\h'+01'\c
203 .\}
204 .el \{\
205 .sp -1
206 .IP "  7." 4.2
207 .\}
208 Using the operators
209 UNION,
210 INTERSECT, and
211 EXCEPT, the output of more than one
212 \fBSELECT\fR
213 statement can be combined to form a single result set\&. The
214 UNION
215 operator returns all rows that are in one or both of the result sets\&. The
216 INTERSECT
217 operator returns all rows that are strictly in both result sets\&. The
218 EXCEPT
219 operator returns the rows that are in the first result set but not in the second\&. In all three cases, duplicate rows are eliminated unless
220 ALL
221 is specified\&. The noise word
222 DISTINCT
223 can be added to explicitly specify eliminating duplicate rows\&. Notice that
224 DISTINCT
225 is the default behavior here, even though
226 ALL
227 is the default for
228 \fBSELECT\fR
229 itself\&. (See
230 UNION Clause,
231 INTERSECT Clause, and
232 EXCEPT Clause
233 below\&.)
234 .RE
235 .sp
236 .RS 4
237 .ie n \{\
238 \h'-04' 8.\h'+01'\c
239 .\}
240 .el \{\
241 .sp -1
242 .IP "  8." 4.2
243 .\}
244 If the
245 ORDER BY
246 clause is specified, the returned rows are sorted in the specified order\&. If
247 ORDER BY
248 is not given, the rows are returned in whatever order the system finds fastest to produce\&. (See
249 ORDER BY Clause
250 below\&.)
251 .RE
252 .sp
253 .RS 4
254 .ie n \{\
255 \h'-04' 9.\h'+01'\c
256 .\}
257 .el \{\
258 .sp -1
259 .IP "  9." 4.2
260 .\}
261 If the
262 LIMIT
263 (or
264 FETCH FIRST) or
265 OFFSET
266 clause is specified, the
267 \fBSELECT\fR
268 statement only returns a subset of the result rows\&. (See
269 LIMIT Clause
270 below\&.)
271 .RE
272 .sp
273 .RS 4
274 .ie n \{\
275 \h'-04'10.\h'+01'\c
276 .\}
277 .el \{\
278 .sp -1
279 .IP "10." 4.2
280 .\}
281 If
282 FOR UPDATE,
283 FOR NO KEY UPDATE,
284 FOR SHARE
285 or
286 FOR KEY SHARE
287 is specified, the
288 \fBSELECT\fR
289 statement locks the selected rows against concurrent updates\&. (See
290 The Locking Clause
291 below\&.)
292 .RE
293 .PP
294 You must have
295 SELECT
296 privilege on each column used in a
297 \fBSELECT\fR
298 command\&. The use of
299 FOR NO KEY UPDATE,
300 FOR UPDATE,
301 FOR SHARE
302 or
303 FOR KEY SHARE
304 requires
305 UPDATE
306 privilege as well (for at least one column of each table so selected)\&.
307 .SH "PARAMETERS"
308 .SS "WITH Clause"
309 .PP
310 The
311 WITH
312 clause allows you to specify one or more subqueries that can be referenced by name in the primary query\&. The subqueries effectively act as temporary tables or views for the duration of the primary query\&. Each subquery can be a
313 \fBSELECT\fR,
314 \fBTABLE\fR,
315 \fBVALUES\fR,
316 \fBINSERT\fR,
317 \fBUPDATE\fR,
318 \fBDELETE\fR, or
319 \fBMERGE\fR
320 statement\&. When writing a data\-modifying statement (\fBINSERT\fR,
321 \fBUPDATE\fR,
322 \fBDELETE\fR, or
323 \fBMERGE\fR) in
324 WITH, it is usual to include a
325 RETURNING
326 clause\&. It is the output of
327 RETURNING,
328 \fInot\fR
329 the underlying table that the statement modifies, that forms the temporary table that is read by the primary query\&. If
330 RETURNING
331 is omitted, the statement is still executed, but it produces no output so it cannot be referenced as a table by the primary query\&.
332 .PP
333 A name (without schema qualification) must be specified for each
334 WITH
335 query\&. Optionally, a list of column names can be specified; if this is omitted, the column names are inferred from the subquery\&.
336 .PP
337 If
338 RECURSIVE
339 is specified, it allows a
340 \fBSELECT\fR
341 subquery to reference itself by name\&. Such a subquery must have the form
342 .sp
343 .if n \{\
344 .RS 4
345 .\}
346 .nf
347 \fInon_recursive_term\fR UNION [ ALL | DISTINCT ] \fIrecursive_term\fR
348 .fi
349 .if n \{\
350 .RE
351 .\}
352 .sp
353 where the recursive self\-reference must appear on the right\-hand side of the
354 UNION\&. Only one recursive self\-reference is permitted per query\&. Recursive data\-modifying statements are not supported, but you can use the results of a recursive
355 \fBSELECT\fR
356 query in a data\-modifying statement\&. See
357 Section\ \&7.8
358 for an example\&.
359 .PP
360 Another effect of
361 RECURSIVE
362 is that
363 WITH
364 queries need not be ordered: a query can reference another one that is later in the list\&. (However, circular references, or mutual recursion, are not implemented\&.) Without
365 RECURSIVE,
366 WITH
367 queries can only reference sibling
368 WITH
369 queries that are earlier in the
370 WITH
371 list\&.
372 .PP
373 When there are multiple queries in the
374 WITH
375 clause,
376 RECURSIVE
377 should be written only once, immediately after
378 WITH\&. It applies to all queries in the
379 WITH
380 clause, though it has no effect on queries that do not use recursion or forward references\&.
381 .PP
382 The optional
383 SEARCH
384 clause computes a
385 search sequence column
386 that can be used for ordering the results of a recursive query in either breadth\-first or depth\-first order\&. The supplied column name list specifies the row key that is to be used for keeping track of visited rows\&. A column named
387 \fIsearch_seq_col_name\fR
388 will be added to the result column list of the
389 WITH
390 query\&. This column can be ordered by in the outer query to achieve the respective ordering\&. See
391 Section\ \&7.8.2.1
392 for examples\&.
393 .PP
394 The optional
395 CYCLE
396 clause is used to detect cycles in recursive queries\&. The supplied column name list specifies the row key that is to be used for keeping track of visited rows\&. A column named
397 \fIcycle_mark_col_name\fR
398 will be added to the result column list of the
399 WITH
400 query\&. This column will be set to
401 \fIcycle_mark_value\fR
402 when a cycle has been detected, else to
403 \fIcycle_mark_default\fR\&. Furthermore, processing of the recursive union will stop when a cycle has been detected\&.
404 \fIcycle_mark_value\fR
405 and
406 \fIcycle_mark_default\fR
407 must be constants and they must be coercible to a common data type, and the data type must have an inequality operator\&. (The SQL standard requires that they be Boolean constants or character strings, but PostgreSQL does not require that\&.) By default,
408 TRUE
409 and
410 FALSE
411 (of type
412 boolean) are used\&. Furthermore, a column named
413 \fIcycle_path_col_name\fR
414 will be added to the result column list of the
415 WITH
416 query\&. This column is used internally for tracking visited rows\&. See
417 Section\ \&7.8.2.2
418 for examples\&.
419 .PP
420 Both the
421 SEARCH
422 and the
423 CYCLE
424 clause are only valid for recursive
425 WITH
426 queries\&. The
427 \fIwith_query\fR
428 must be a
429 UNION
430 (or
431 UNION ALL) of two
432 SELECT
433 (or equivalent) commands (no nested
434 UNIONs)\&. If both clauses are used, the column added by the
435 SEARCH
436 clause appears before the columns added by the
437 CYCLE
438 clause\&.
439 .PP
440 The primary query and the
441 WITH
442 queries are all (notionally) executed at the same time\&. This implies that the effects of a data\-modifying statement in
443 WITH
444 cannot be seen from other parts of the query, other than by reading its
445 RETURNING
446 output\&. If two such data\-modifying statements attempt to modify the same row, the results are unspecified\&.
447 .PP
448 A key property of
449 WITH
450 queries is that they are normally evaluated only once per execution of the primary query, even if the primary query refers to them more than once\&. In particular, data\-modifying statements are guaranteed to be executed once and only once, regardless of whether the primary query reads all or any of their output\&.
451 .PP
452 However, a
453 WITH
454 query can be marked
455 NOT MATERIALIZED
456 to remove this guarantee\&. In that case, the
457 WITH
458 query can be folded into the primary query much as though it were a simple sub\-SELECT
459 in the primary query\*(Aqs
460 FROM
461 clause\&. This results in duplicate computations if the primary query refers to that
462 WITH
463 query more than once; but if each such use requires only a few rows of the
464 WITH
465 query\*(Aqs total output,
466 NOT MATERIALIZED
467 can provide a net savings by allowing the queries to be optimized jointly\&.
468 NOT MATERIALIZED
469 is ignored if it is attached to a
470 WITH
471 query that is recursive or is not side\-effect\-free (i\&.e\&., is not a plain
472 SELECT
473 containing no volatile functions)\&.
474 .PP
475 By default, a side\-effect\-free
476 WITH
477 query is folded into the primary query if it is used exactly once in the primary query\*(Aqs
478 FROM
479 clause\&. This allows joint optimization of the two query levels in situations where that should be semantically invisible\&. However, such folding can be prevented by marking the
480 WITH
481 query as
482 MATERIALIZED\&. That might be useful, for example, if the
483 WITH
484 query is being used as an optimization fence to prevent the planner from choosing a bad plan\&.
485 PostgreSQL
486 versions before v12 never did such folding, so queries written for older versions might rely on
487 WITH
488 to act as an optimization fence\&.
489 .PP
490 See
491 Section\ \&7.8
492 for additional information\&.
493 .SS "FROM Clause"
494 .PP
495 The
496 FROM
497 clause specifies one or more source tables for the
498 \fBSELECT\fR\&. If multiple sources are specified, the result is the Cartesian product (cross join) of all the sources\&. But usually qualification conditions are added (via
499 WHERE) to restrict the returned rows to a small subset of the Cartesian product\&.
500 .PP
501 The
502 FROM
503 clause can contain the following elements:
504 .PP
505 \fItable_name\fR
506 .RS 4
507 The name (optionally schema\-qualified) of an existing table or view\&. If
508 ONLY
509 is specified before the table name, only that table is scanned\&. If
510 ONLY
511 is not specified, the table and all its descendant tables (if any) are scanned\&. Optionally,
512 *
513 can be specified after the table name to explicitly indicate that descendant tables are included\&.
514 .RE
515 .PP
516 \fIalias\fR
517 .RS 4
518 A substitute name for the
519 FROM
520 item containing the alias\&. An alias is used for brevity or to eliminate ambiguity for self\-joins (where the same table is scanned multiple times)\&. When an alias is provided, it completely hides the actual name of the table or function; for example given
521 FROM foo AS f, the remainder of the
522 \fBSELECT\fR
523 must refer to this
524 FROM
525 item as
526 f
527 not
528 foo\&. If an alias is written, a column alias list can also be written to provide substitute names for one or more columns of the table\&.
529 .RE
530 .PP
531 TABLESAMPLE \fIsampling_method\fR ( \fIargument\fR [, \&.\&.\&.] ) [ REPEATABLE ( \fIseed\fR ) ]
532 .RS 4
533 A
534 TABLESAMPLE
535 clause after a
536 \fItable_name\fR
537 indicates that the specified
538 \fIsampling_method\fR
539 should be used to retrieve a subset of the rows in that table\&. This sampling precedes the application of any other filters such as
540 WHERE
541 clauses\&. The standard
542 PostgreSQL
543 distribution includes two sampling methods,
544 BERNOULLI
545 and
546 SYSTEM, and other sampling methods can be installed in the database via extensions\&.
547 .sp
548 The
549 BERNOULLI
550 and
551 SYSTEM
552 sampling methods each accept a single
553 \fIargument\fR
554 which is the fraction of the table to sample, expressed as a percentage between 0 and 100\&. This argument can be any
555 real\-valued expression\&. (Other sampling methods might accept more or different arguments\&.) These two methods each return a randomly\-chosen sample of the table that will contain approximately the specified percentage of the table\*(Aqs rows\&. The
556 BERNOULLI
557 method scans the whole table and selects or ignores individual rows independently with the specified probability\&. The
558 SYSTEM
559 method does block\-level sampling with each block having the specified chance of being selected; all rows in each selected block are returned\&. The
560 SYSTEM
561 method is significantly faster than the
562 BERNOULLI
563 method when small sampling percentages are specified, but it may return a less\-random sample of the table as a result of clustering effects\&.
564 .sp
565 The optional
566 REPEATABLE
567 clause specifies a
568 \fIseed\fR
569 number or expression to use for generating random numbers within the sampling method\&. The seed value can be any non\-null floating\-point value\&. Two queries that specify the same seed and
570 \fIargument\fR
571 values will select the same sample of the table, if the table has not been changed meanwhile\&. But different seed values will usually produce different samples\&. If
572 REPEATABLE
573 is not given then a new random sample is selected for each query, based upon a system\-generated seed\&. Note that some add\-on sampling methods do not accept
574 REPEATABLE, and will always produce new samples on each use\&.
575 .RE
576 .PP
577 \fIselect\fR
578 .RS 4
579 A sub\-\fBSELECT\fR
580 can appear in the
581 FROM
582 clause\&. This acts as though its output were created as a temporary table for the duration of this single
583 \fBSELECT\fR
584 command\&. Note that the sub\-\fBSELECT\fR
585 must be surrounded by parentheses, and an alias can be provided in the same way as for a table\&. A
586 \fBVALUES\fR
587 command can also be used here\&.
588 .RE
589 .PP
590 \fIwith_query_name\fR
591 .RS 4
592 A
593 WITH
594 query is referenced by writing its name, just as though the query\*(Aqs name were a table name\&. (In fact, the
595 WITH
596 query hides any real table of the same name for the purposes of the primary query\&. If necessary, you can refer to a real table of the same name by schema\-qualifying the table\*(Aqs name\&.) An alias can be provided in the same way as for a table\&.
597 .RE
598 .PP
599 \fIfunction_name\fR
600 .RS 4
601 Function calls can appear in the
602 FROM
603 clause\&. (This is especially useful for functions that return result sets, but any function can be used\&.) This acts as though the function\*(Aqs output were created as a temporary table for the duration of this single
604 \fBSELECT\fR
605 command\&. If the function\*(Aqs result type is composite (including the case of a function with multiple
606 OUT
607 parameters), each attribute becomes a separate column in the implicit table\&.
608 .sp
609 When the optional
610 \fBWITH ORDINALITY\fR
611 clause is added to the function call, an additional column of type
612 bigint
613 will be appended to the function\*(Aqs result column(s)\&. This column numbers the rows of the function\*(Aqs result set, starting from 1\&. By default, this column is named
614 ordinality\&.
615 .sp
616 An alias can be provided in the same way as for a table\&. If an alias is written, a column alias list can also be written to provide substitute names for one or more attributes of the function\*(Aqs composite return type, including the ordinality column if present\&.
617 .sp
618 Multiple function calls can be combined into a single
619 FROM\-clause item by surrounding them with
620 ROWS FROM( \&.\&.\&. )\&. The output of such an item is the concatenation of the first row from each function, then the second row from each function, etc\&. If some of the functions produce fewer rows than others, null values are substituted for the missing data, so that the total number of rows returned is always the same as for the function that produced the most rows\&.
621 .sp
622 If the function has been defined as returning the
623 record
624 data type, then an alias or the key word
625 AS
626 must be present, followed by a column definition list in the form
627 ( \fIcolumn_name\fR \fIdata_type\fR [, \&.\&.\&. ])\&. The column definition list must match the actual number and types of columns returned by the function\&.
628 .sp
629 When using the
630 ROWS FROM( \&.\&.\&. )
631 syntax, if one of the functions requires a column definition list, it\*(Aqs preferred to put the column definition list after the function call inside
632 ROWS FROM( \&.\&.\&. )\&. A column definition list can be placed after the
633 ROWS FROM( \&.\&.\&. )
634 construct only if there\*(Aqs just a single function and no
635 WITH ORDINALITY
636 clause\&.
637 .sp
638 To use
639 ORDINALITY
640 together with a column definition list, you must use the
641 ROWS FROM( \&.\&.\&. )
642 syntax and put the column definition list inside
643 ROWS FROM( \&.\&.\&. )\&.
644 .RE
645 .PP
646 \fIjoin_type\fR
647 .RS 4
648 One of
649 .sp
650 .RS 4
651 .ie n \{\
652 \h'-04'\(bu\h'+03'\c
653 .\}
654 .el \{\
655 .sp -1
656 .IP \(bu 2.3
657 .\}
658 [ INNER ] JOIN
659 .RE
660 .sp
661 .RS 4
662 .ie n \{\
663 \h'-04'\(bu\h'+03'\c
664 .\}
665 .el \{\
666 .sp -1
667 .IP \(bu 2.3
668 .\}
669 LEFT [ OUTER ] JOIN
670 .RE
671 .sp
672 .RS 4
673 .ie n \{\
674 \h'-04'\(bu\h'+03'\c
675 .\}
676 .el \{\
677 .sp -1
678 .IP \(bu 2.3
679 .\}
680 RIGHT [ OUTER ] JOIN
681 .RE
682 .sp
683 .RS 4
684 .ie n \{\
685 \h'-04'\(bu\h'+03'\c
686 .\}
687 .el \{\
688 .sp -1
689 .IP \(bu 2.3
690 .\}
691 FULL [ OUTER ] JOIN
692 .RE
693 .sp
694 For the
695 INNER
696 and
697 OUTER
698 join types, a join condition must be specified, namely exactly one of
699 ON \fIjoin_condition\fR,
700 USING (\fIjoin_column\fR [, \&.\&.\&.]), or
701 NATURAL\&. See below for the meaning\&.
702 .sp
703 A
704 JOIN
705 clause combines two
706 FROM
707 items, which for convenience we will refer to as
708 \(lqtables\(rq, though in reality they can be any type of
709 FROM
710 item\&. Use parentheses if necessary to determine the order of nesting\&. In the absence of parentheses,
711 JOINs nest left\-to\-right\&. In any case
712 JOIN
713 binds more tightly than the commas separating
714 FROM\-list items\&. All the
715 JOIN
716 options are just a notational convenience, since they do nothing you couldn\*(Aqt do with plain
717 FROM
718 and
719 WHERE\&.
720 .sp
721 LEFT OUTER JOIN
722 returns all rows in the qualified Cartesian product (i\&.e\&., all combined rows that pass its join condition), plus one copy of each row in the left\-hand table for which there was no right\-hand row that passed the join condition\&. This left\-hand row is extended to the full width of the joined table by inserting null values for the right\-hand columns\&. Note that only the
723 JOIN
724 clause\*(Aqs own condition is considered while deciding which rows have matches\&. Outer conditions are applied afterwards\&.
725 .sp
726 Conversely,
727 RIGHT OUTER JOIN
728 returns all the joined rows, plus one row for each unmatched right\-hand row (extended with nulls on the left)\&. This is just a notational convenience, since you could convert it to a
729 LEFT OUTER JOIN
730 by switching the left and right tables\&.
731 .sp
732 FULL OUTER JOIN
733 returns all the joined rows, plus one row for each unmatched left\-hand row (extended with nulls on the right), plus one row for each unmatched right\-hand row (extended with nulls on the left)\&.
734 .RE
735 .PP
736 ON \fIjoin_condition\fR
737 .RS 4
738 \fIjoin_condition\fR
739 is an expression resulting in a value of type
740 boolean
741 (similar to a
742 WHERE
743 clause) that specifies which rows in a join are considered to match\&.
744 .RE
745 .PP
746 USING ( \fIjoin_column\fR [, \&.\&.\&.] ) [ AS \fIjoin_using_alias\fR ]
747 .RS 4
748 A clause of the form
749 USING ( a, b, \&.\&.\&. )
750 is shorthand for
751 ON left_table\&.a = right_table\&.a AND left_table\&.b = right_table\&.b \&.\&.\&.\&. Also,
752 USING
753 implies that only one of each pair of equivalent columns will be included in the join output, not both\&.
754 .sp
755 If a
756 \fIjoin_using_alias\fR
757 name is specified, it provides a table alias for the join columns\&. Only the join columns listed in the
758 USING
759 clause are addressable by this name\&. Unlike a regular
760 \fIalias\fR, this does not hide the names of the joined tables from the rest of the query\&. Also unlike a regular
761 \fIalias\fR, you cannot write a column alias list \(em the output names of the join columns are the same as they appear in the
762 USING
763 list\&.
764 .RE
765 .PP
766 NATURAL
767 .RS 4
768 NATURAL
769 is shorthand for a
770 USING
771 list that mentions all columns in the two tables that have matching names\&. If there are no common column names,
772 NATURAL
773 is equivalent to
774 ON TRUE\&.
775 .RE
776 .PP
777 CROSS JOIN
778 .RS 4
779 CROSS JOIN
780 is equivalent to
781 INNER JOIN ON (TRUE), that is, no rows are removed by qualification\&. They produce a simple Cartesian product, the same result as you get from listing the two tables at the top level of
782 FROM, but restricted by the join condition (if any)\&.
783 .RE
784 .PP
785 LATERAL
786 .RS 4
787 The
788 LATERAL
789 key word can precede a sub\-\fBSELECT\fR
790 FROM
791 item\&. This allows the sub\-\fBSELECT\fR
792 to refer to columns of
793 FROM
794 items that appear before it in the
795 FROM
796 list\&. (Without
797 LATERAL, each sub\-\fBSELECT\fR
798 is evaluated independently and so cannot cross\-reference any other
799 FROM
800 item\&.)
801 .sp
802 LATERAL
803 can also precede a function\-call
804 FROM
805 item, but in this case it is a noise word, because the function expression can refer to earlier
806 FROM
807 items in any case\&.
808 .sp
809 A
810 LATERAL
811 item can appear at top level in the
812 FROM
813 list, or within a
814 JOIN
815 tree\&. In the latter case it can also refer to any items that are on the left\-hand side of a
816 JOIN
817 that it is on the right\-hand side of\&.
818 .sp
819 When a
820 FROM
821 item contains
822 LATERAL
823 cross\-references, evaluation proceeds as follows: for each row of the
824 FROM
825 item providing the cross\-referenced column(s), or set of rows of multiple
826 FROM
827 items providing the columns, the
828 LATERAL
829 item is evaluated using that row or row set\*(Aqs values of the columns\&. The resulting row(s) are joined as usual with the rows they were computed from\&. This is repeated for each row or set of rows from the column source table(s)\&.
830 .sp
831 The column source table(s) must be
832 INNER
833 or
834 LEFT
835 joined to the
836 LATERAL
837 item, else there would not be a well\-defined set of rows from which to compute each set of rows for the
838 LATERAL
839 item\&. Thus, although a construct such as
840 \fIX\fR RIGHT JOIN LATERAL \fIY\fR
841 is syntactically valid, it is not actually allowed for
842 \fIY\fR
843 to reference
844 \fIX\fR\&.
845 .RE
846 .SS "WHERE Clause"
847 .PP
848 The optional
849 WHERE
850 clause has the general form
851 .sp
852 .if n \{\
853 .RS 4
854 .\}
855 .nf
856 WHERE \fIcondition\fR
857 .fi
858 .if n \{\
859 .RE
860 .\}
861 .sp
862 where
863 \fIcondition\fR
864 is any expression that evaluates to a result of type
865 boolean\&. Any row that does not satisfy this condition will be eliminated from the output\&. A row satisfies the condition if it returns true when the actual row values are substituted for any variable references\&.
866 .SS "GROUP BY Clause"
867 .PP
868 The optional
869 GROUP BY
870 clause has the general form
871 .sp
872 .if n \{\
873 .RS 4
874 .\}
875 .nf
876 GROUP BY [ ALL | DISTINCT ] \fIgrouping_element\fR [, \&.\&.\&.]
877 .fi
878 .if n \{\
879 .RE
880 .\}
881 .PP
882 GROUP BY
883 will condense into a single row all selected rows that share the same values for the grouped expressions\&. An
884 \fIexpression\fR
885 used inside a
886 \fIgrouping_element\fR
887 can be an input column name, or the name or ordinal number of an output column (\fBSELECT\fR
888 list item), or an arbitrary expression formed from input\-column values\&. In case of ambiguity, a
889 GROUP BY
890 name will be interpreted as an input\-column name rather than an output column name\&.
891 .PP
892 If any of
893 GROUPING SETS,
894 ROLLUP
895 or
896 CUBE
897 are present as grouping elements, then the
898 GROUP BY
899 clause as a whole defines some number of independent
900 \fIgrouping sets\fR\&. The effect of this is equivalent to constructing a
901 UNION ALL
902 between subqueries with the individual grouping sets as their
903 GROUP BY
904 clauses\&. The optional
905 DISTINCT
906 clause removes duplicate sets before processing; it does
907 \fInot\fR
908 transform the
909 UNION ALL
910 into a
911 UNION DISTINCT\&. For further details on the handling of grouping sets see
912 Section\ \&7.2.4\&.
913 .PP
914 Aggregate functions, if any are used, are computed across all rows making up each group, producing a separate value for each group\&. (If there are aggregate functions but no
915 GROUP BY
916 clause, the query is treated as having a single group comprising all the selected rows\&.) The set of rows fed to each aggregate function can be further filtered by attaching a
917 FILTER
918 clause to the aggregate function call; see
919 Section\ \&4.2.7
920 for more information\&. When a
921 FILTER
922 clause is present, only those rows matching it are included in the input to that aggregate function\&.
923 .PP
924 When
925 GROUP BY
926 is present, or any aggregate functions are present, it is not valid for the
927 \fBSELECT\fR
928 list expressions to refer to ungrouped columns except within aggregate functions or when the ungrouped column is functionally dependent on the grouped columns, since there would otherwise be more than one possible value to return for an ungrouped column\&. A functional dependency exists if the grouped columns (or a subset thereof) are the primary key of the table containing the ungrouped column\&.
929 .PP
930 Keep in mind that all aggregate functions are evaluated before evaluating any
931 \(lqscalar\(rq
932 expressions in the
933 HAVING
934 clause or
935 SELECT
936 list\&. This means that, for example, a
937 CASE
938 expression cannot be used to skip evaluation of an aggregate function; see
939 Section\ \&4.2.14\&.
940 .PP
941 Currently,
942 FOR NO KEY UPDATE,
943 FOR UPDATE,
944 FOR SHARE
945 and
946 FOR KEY SHARE
947 cannot be specified with
948 GROUP BY\&.
949 .SS "HAVING Clause"
950 .PP
951 The optional
952 HAVING
953 clause has the general form
954 .sp
955 .if n \{\
956 .RS 4
957 .\}
958 .nf
959 HAVING \fIcondition\fR
960 .fi
961 .if n \{\
962 .RE
963 .\}
964 .sp
965 where
966 \fIcondition\fR
967 is the same as specified for the
968 WHERE
969 clause\&.
970 .PP
971 HAVING
972 eliminates group rows that do not satisfy the condition\&.
973 HAVING
974 is different from
975 WHERE:
976 WHERE
977 filters individual rows before the application of
978 GROUP BY, while
979 HAVING
980 filters group rows created by
981 GROUP BY\&. Each column referenced in
982 \fIcondition\fR
983 must unambiguously reference a grouping column, unless the reference appears within an aggregate function or the ungrouped column is functionally dependent on the grouping columns\&.
984 .PP
985 The presence of
986 HAVING
987 turns a query into a grouped query even if there is no
988 GROUP BY
989 clause\&. This is the same as what happens when the query contains aggregate functions but no
990 GROUP BY
991 clause\&. All the selected rows are considered to form a single group, and the
992 \fBSELECT\fR
993 list and
994 HAVING
995 clause can only reference table columns from within aggregate functions\&. Such a query will emit a single row if the
996 HAVING
997 condition is true, zero rows if it is not true\&.
998 .PP
999 Currently,
1000 FOR NO KEY UPDATE,
1001 FOR UPDATE,
1002 FOR SHARE
1003 and
1004 FOR KEY SHARE
1005 cannot be specified with
1006 HAVING\&.
1007 .SS "WINDOW Clause"
1008 .PP
1009 The optional
1010 WINDOW
1011 clause has the general form
1012 .sp
1013 .if n \{\
1014 .RS 4
1015 .\}
1016 .nf
1017 WINDOW \fIwindow_name\fR AS ( \fIwindow_definition\fR ) [, \&.\&.\&.]
1018 .fi
1019 .if n \{\
1020 .RE
1021 .\}
1022 .sp
1023 where
1024 \fIwindow_name\fR
1025 is a name that can be referenced from
1026 OVER
1027 clauses or subsequent window definitions, and
1028 \fIwindow_definition\fR
1029 is
1030 .sp
1031 .if n \{\
1032 .RS 4
1033 .\}
1034 .nf
1035 [ \fIexisting_window_name\fR ]
1036 [ PARTITION BY \fIexpression\fR [, \&.\&.\&.] ]
1037 [ ORDER BY \fIexpression\fR [ ASC | DESC | USING \fIoperator\fR ] [ NULLS { FIRST | LAST } ] [, \&.\&.\&.] ]
1038 [ \fIframe_clause\fR ]
1039 .fi
1040 .if n \{\
1041 .RE
1042 .\}
1043 .PP
1044 If an
1045 \fIexisting_window_name\fR
1046 is specified it must refer to an earlier entry in the
1047 WINDOW
1048 list; the new window copies its partitioning clause from that entry, as well as its ordering clause if any\&. In this case the new window cannot specify its own
1049 PARTITION BY
1050 clause, and it can specify
1051 ORDER BY
1052 only if the copied window does not have one\&. The new window always uses its own frame clause; the copied window must not specify a frame clause\&.
1053 .PP
1054 The elements of the
1055 PARTITION BY
1056 list are interpreted in much the same fashion as elements of a
1057 GROUP BY
1058 clause, except that they are always simple expressions and never the name or number of an output column\&. Another difference is that these expressions can contain aggregate function calls, which are not allowed in a regular
1059 GROUP BY
1060 clause\&. They are allowed here because windowing occurs after grouping and aggregation\&.
1061 .PP
1062 Similarly, the elements of the
1063 ORDER BY
1064 list are interpreted in much the same fashion as elements of a statement\-level
1065 ORDER BY
1066 clause, except that the expressions are always taken as simple expressions and never the name or number of an output column\&.
1067 .PP
1068 The optional
1069 \fIframe_clause\fR
1070 defines the
1071 window frame
1072 for window functions that depend on the frame (not all do)\&. The window frame is a set of related rows for each row of the query (called the
1073 current row)\&. The
1074 \fIframe_clause\fR
1075 can be one of
1076 .sp
1077 .if n \{\
1078 .RS 4
1079 .\}
1080 .nf
1081 { RANGE | ROWS | GROUPS } \fIframe_start\fR [ \fIframe_exclusion\fR ]
1082 { RANGE | ROWS | GROUPS } BETWEEN \fIframe_start\fR AND \fIframe_end\fR [ \fIframe_exclusion\fR ]
1083 .fi
1084 .if n \{\
1085 .RE
1086 .\}
1087 .sp
1088 where
1089 \fIframe_start\fR
1090 and
1091 \fIframe_end\fR
1092 can be one of
1093 .sp
1094 .if n \{\
1095 .RS 4
1096 .\}
1097 .nf
1098 UNBOUNDED PRECEDING
1099 \fIoffset\fR PRECEDING
1100 CURRENT ROW
1101 \fIoffset\fR FOLLOWING
1102 UNBOUNDED FOLLOWING
1103 .fi
1104 .if n \{\
1105 .RE
1106 .\}
1107 .sp
1108 and
1109 \fIframe_exclusion\fR
1110 can be one of
1111 .sp
1112 .if n \{\
1113 .RS 4
1114 .\}
1115 .nf
1116 EXCLUDE CURRENT ROW
1117 EXCLUDE GROUP
1118 EXCLUDE TIES
1119 EXCLUDE NO OTHERS
1120 .fi
1121 .if n \{\
1122 .RE
1123 .\}
1124 .sp
1125 If
1126 \fIframe_end\fR
1127 is omitted it defaults to
1128 CURRENT ROW\&. Restrictions are that
1129 \fIframe_start\fR
1130 cannot be
1131 UNBOUNDED FOLLOWING,
1132 \fIframe_end\fR
1133 cannot be
1134 UNBOUNDED PRECEDING, and the
1135 \fIframe_end\fR
1136 choice cannot appear earlier in the above list of
1137 \fIframe_start\fR
1138 and
1139 \fIframe_end\fR
1140 options than the
1141 \fIframe_start\fR
1142 choice does \(em for example
1143 RANGE BETWEEN CURRENT ROW AND \fIoffset\fR PRECEDING
1144 is not allowed\&.
1145 .PP
1146 The default framing option is
1147 RANGE UNBOUNDED PRECEDING, which is the same as
1148 RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW; it sets the frame to be all rows from the partition start up through the current row\*(Aqs last
1149 peer
1150 (a row that the window\*(Aqs
1151 ORDER BY
1152 clause considers equivalent to the current row; all rows are peers if there is no
1153 ORDER BY)\&. In general,
1154 UNBOUNDED PRECEDING
1155 means that the frame starts with the first row of the partition, and similarly
1156 UNBOUNDED FOLLOWING
1157 means that the frame ends with the last row of the partition, regardless of
1158 RANGE,
1159 ROWS
1160 or
1161 GROUPS
1162 mode\&. In
1163 ROWS
1164 mode,
1165 CURRENT ROW
1166 means that the frame starts or ends with the current row; but in
1167 RANGE
1168 or
1169 GROUPS
1170 mode it means that the frame starts or ends with the current row\*(Aqs first or last peer in the
1171 ORDER BY
1172 ordering\&. The
1173 \fIoffset\fR
1174 PRECEDING
1175 and
1176 \fIoffset\fR
1177 FOLLOWING
1178 options vary in meaning depending on the frame mode\&. In
1179 ROWS
1180 mode, the
1181 \fIoffset\fR
1182 is an integer indicating that the frame starts or ends that many rows before or after the current row\&. In
1183 GROUPS
1184 mode, the
1185 \fIoffset\fR
1186 is an integer indicating that the frame starts or ends that many peer groups before or after the current row\*(Aqs peer group, where a
1187 peer group
1188 is a group of rows that are equivalent according to the window\*(Aqs
1189 ORDER BY
1190 clause\&. In
1191 RANGE
1192 mode, use of an
1193 \fIoffset\fR
1194 option requires that there be exactly one
1195 ORDER BY
1196 column in the window definition\&. Then the frame contains those rows whose ordering column value is no more than
1197 \fIoffset\fR
1198 less than (for
1199 PRECEDING) or more than (for
1200 FOLLOWING) the current row\*(Aqs ordering column value\&. In these cases the data type of the
1201 \fIoffset\fR
1202 expression depends on the data type of the ordering column\&. For numeric ordering columns it is typically of the same type as the ordering column, but for datetime ordering columns it is an
1203 interval\&. In all these cases, the value of the
1204 \fIoffset\fR
1205 must be non\-null and non\-negative\&. Also, while the
1206 \fIoffset\fR
1207 does not have to be a simple constant, it cannot contain variables, aggregate functions, or window functions\&.
1208 .PP
1209 The
1210 \fIframe_exclusion\fR
1211 option allows rows around the current row to be excluded from the frame, even if they would be included according to the frame start and frame end options\&.
1212 EXCLUDE CURRENT ROW
1213 excludes the current row from the frame\&.
1214 EXCLUDE GROUP
1215 excludes the current row and its ordering peers from the frame\&.
1216 EXCLUDE TIES
1217 excludes any peers of the current row from the frame, but not the current row itself\&.
1218 EXCLUDE NO OTHERS
1219 simply specifies explicitly the default behavior of not excluding the current row or its peers\&.
1220 .PP
1221 Beware that the
1222 ROWS
1223 mode can produce unpredictable results if the
1224 ORDER BY
1225 ordering does not order the rows uniquely\&. The
1226 RANGE
1227 and
1228 GROUPS
1229 modes are designed to ensure that rows that are peers in the
1230 ORDER BY
1231 ordering are treated alike: all rows of a given peer group will be in the frame or excluded from it\&.
1232 .PP
1233 The purpose of a
1234 WINDOW
1235 clause is to specify the behavior of
1236 window functions
1237 appearing in the query\*(Aqs
1238 \fBSELECT\fR list
1239 or
1240 ORDER BY
1241 clause\&. These functions can reference the
1242 WINDOW
1243 clause entries by name in their
1244 OVER
1245 clauses\&. A
1246 WINDOW
1247 clause entry does not have to be referenced anywhere, however; if it is not used in the query it is simply ignored\&. It is possible to use window functions without any
1248 WINDOW
1249 clause at all, since a window function call can specify its window definition directly in its
1250 OVER
1251 clause\&. However, the
1252 WINDOW
1253 clause saves typing when the same window definition is needed for more than one window function\&.
1254 .PP
1255 Currently,
1256 FOR NO KEY UPDATE,
1257 FOR UPDATE,
1258 FOR SHARE
1259 and
1260 FOR KEY SHARE
1261 cannot be specified with
1262 WINDOW\&.
1263 .PP
1264 Window functions are described in detail in
1265 Section\ \&3.5,
1266 Section\ \&4.2.8, and
1267 Section\ \&7.2.5\&.
1268 .SS "SELECT List"
1269 .PP
1270 The
1271 \fBSELECT\fR
1272 list (between the key words
1273 SELECT
1274 and
1275 FROM) specifies expressions that form the output rows of the
1276 \fBSELECT\fR
1277 statement\&. The expressions can (and usually do) refer to columns computed in the
1278 FROM
1279 clause\&.
1280 .PP
1281 Just as in a table, every output column of a
1282 \fBSELECT\fR
1283 has a name\&. In a simple
1284 \fBSELECT\fR
1285 this name is just used to label the column for display, but when the
1286 \fBSELECT\fR
1287 is a sub\-query of a larger query, the name is seen by the larger query as the column name of the virtual table produced by the sub\-query\&. To specify the name to use for an output column, write
1288 AS
1289 \fIoutput_name\fR
1290 after the column\*(Aqs expression\&. (You can omit
1291 AS, but only if the desired output name does not match any
1292 PostgreSQL
1293 keyword (see
1294 Appendix\ \&C)\&. For protection against possible future keyword additions, it is recommended that you always either write
1295 AS
1296 or double\-quote the output name\&.) If you do not specify a column name, a name is chosen automatically by
1297 PostgreSQL\&. If the column\*(Aqs expression is a simple column reference then the chosen name is the same as that column\*(Aqs name\&. In more complex cases a function or type name may be used, or the system may fall back on a generated name such as
1298 ?column?\&.
1299 .PP
1300 An output column\*(Aqs name can be used to refer to the column\*(Aqs value in
1301 ORDER BY
1302 and
1303 GROUP BY
1304 clauses, but not in the
1305 WHERE
1306 or
1307 HAVING
1308 clauses; there you must write out the expression instead\&.
1309 .PP
1310 Instead of an expression,
1311 *
1312 can be written in the output list as a shorthand for all the columns of the selected rows\&. Also, you can write
1313 \fItable_name\fR\&.*
1314 as a shorthand for the columns coming from just that table\&. In these cases it is not possible to specify new names with
1315 AS; the output column names will be the same as the table columns\*(Aq names\&.
1316 .PP
1317 According to the SQL standard, the expressions in the output list should be computed before applying
1318 DISTINCT,
1319 ORDER BY, or
1320 LIMIT\&. This is obviously necessary when using
1321 DISTINCT, since otherwise it\*(Aqs not clear what values are being made distinct\&. However, in many cases it is convenient if output expressions are computed after
1322 ORDER BY
1323 and
1324 LIMIT; particularly if the output list contains any volatile or expensive functions\&. With that behavior, the order of function evaluations is more intuitive and there will not be evaluations corresponding to rows that never appear in the output\&.
1325 PostgreSQL
1326 will effectively evaluate output expressions after sorting and limiting, so long as those expressions are not referenced in
1327 DISTINCT,
1328 ORDER BY
1329 or
1330 GROUP BY\&. (As a counterexample,
1331 SELECT f(x) FROM tab ORDER BY 1
1332 clearly must evaluate
1333 \fBf(x)\fR
1334 before sorting\&.) Output expressions that contain set\-returning functions are effectively evaluated after sorting and before limiting, so that
1335 LIMIT
1336 will act to cut off the output from a set\-returning function\&.
1337 .if n \{\
1338 .sp
1339 .\}
1340 .RS 4
1341 .it 1 an-trap
1342 .nr an-no-space-flag 1
1343 .nr an-break-flag 1
1344 .br
1345 .ps +1
1346 \fBNote\fR
1347 .ps -1
1348 .br
1349 .PP
1350 PostgreSQL
1351 versions before 9\&.6 did not provide any guarantees about the timing of evaluation of output expressions versus sorting and limiting; it depended on the form of the chosen query plan\&.
1352 .sp .5v
1353 .RE
1354 .SS "DISTINCT Clause"
1355 .PP
1356 If
1357 SELECT DISTINCT
1358 is specified, all duplicate rows are removed from the result set (one row is kept from each group of duplicates)\&.
1359 SELECT ALL
1360 specifies the opposite: all rows are kept; that is the default\&.
1361 .PP
1362 SELECT DISTINCT ON ( \fIexpression\fR [, \&.\&.\&.] )
1363 keeps only the first row of each set of rows where the given expressions evaluate to equal\&. The
1364 DISTINCT ON
1365 expressions are interpreted using the same rules as for
1366 ORDER BY
1367 (see above)\&. Note that the
1368 \(lqfirst row\(rq
1369 of each set is unpredictable unless
1370 ORDER BY
1371 is used to ensure that the desired row appears first\&. For example:
1372 .sp
1373 .if n \{\
1374 .RS 4
1375 .\}
1376 .nf
1377 SELECT DISTINCT ON (location) location, time, report
1378     FROM weather_reports
1379     ORDER BY location, time DESC;
1380 .fi
1381 .if n \{\
1382 .RE
1383 .\}
1384 .sp
1385 retrieves the most recent weather report for each location\&. But if we had not used
1386 ORDER BY
1387 to force descending order of time values for each location, we\*(Aqd have gotten a report from an unpredictable time for each location\&.
1388 .PP
1389 The
1390 DISTINCT ON
1391 expression(s) must match the leftmost
1392 ORDER BY
1393 expression(s)\&. The
1394 ORDER BY
1395 clause will normally contain additional expression(s) that determine the desired precedence of rows within each
1396 DISTINCT ON
1397 group\&.
1398 .PP
1399 Currently,
1400 FOR NO KEY UPDATE,
1401 FOR UPDATE,
1402 FOR SHARE
1403 and
1404 FOR KEY SHARE
1405 cannot be specified with
1406 DISTINCT\&.
1407 .SS "UNION Clause"
1408 .PP
1409 The
1410 UNION
1411 clause has this general form:
1412 .sp
1413 .if n \{\
1414 .RS 4
1415 .\}
1416 .nf
1417 \fIselect_statement\fR UNION [ ALL | DISTINCT ] \fIselect_statement\fR
1418 .fi
1419 .if n \{\
1420 .RE
1421 .\}
1422 .sp
1423 \fIselect_statement\fR
1424 is any
1425 \fBSELECT\fR
1426 statement without an
1427 ORDER BY,
1428 LIMIT,
1429 FOR NO KEY UPDATE,
1430 FOR UPDATE,
1431 FOR SHARE, or
1432 FOR KEY SHARE
1433 clause\&. (ORDER BY
1434 and
1435 LIMIT
1436 can be attached to a subexpression if it is enclosed in parentheses\&. Without parentheses, these clauses will be taken to apply to the result of the
1437 UNION, not to its right\-hand input expression\&.)
1438 .PP
1439 The
1440 UNION
1441 operator computes the set union of the rows returned by the involved
1442 \fBSELECT\fR
1443 statements\&. A row is in the set union of two result sets if it appears in at least one of the result sets\&. The two
1444 \fBSELECT\fR
1445 statements that represent the direct operands of the
1446 UNION
1447 must produce the same number of columns, and corresponding columns must be of compatible data types\&.
1448 .PP
1449 The result of
1450 UNION
1451 does not contain any duplicate rows unless the
1452 ALL
1453 option is specified\&.
1454 ALL
1455 prevents elimination of duplicates\&. (Therefore,
1456 UNION ALL
1457 is usually significantly quicker than
1458 UNION; use
1459 ALL
1460 when you can\&.)
1461 DISTINCT
1462 can be written to explicitly specify the default behavior of eliminating duplicate rows\&.
1463 .PP
1464 Multiple
1465 UNION
1466 operators in the same
1467 \fBSELECT\fR
1468 statement are evaluated left to right, unless otherwise indicated by parentheses\&.
1469 .PP
1470 Currently,
1471 FOR NO KEY UPDATE,
1472 FOR UPDATE,
1473 FOR SHARE
1474 and
1475 FOR KEY SHARE
1476 cannot be specified either for a
1477 UNION
1478 result or for any input of a
1479 UNION\&.
1480 .SS "INTERSECT Clause"
1481 .PP
1482 The
1483 INTERSECT
1484 clause has this general form:
1485 .sp
1486 .if n \{\
1487 .RS 4
1488 .\}
1489 .nf
1490 \fIselect_statement\fR INTERSECT [ ALL | DISTINCT ] \fIselect_statement\fR
1491 .fi
1492 .if n \{\
1493 .RE
1494 .\}
1495 .sp
1496 \fIselect_statement\fR
1497 is any
1498 \fBSELECT\fR
1499 statement without an
1500 ORDER BY,
1501 LIMIT,
1502 FOR NO KEY UPDATE,
1503 FOR UPDATE,
1504 FOR SHARE, or
1505 FOR KEY SHARE
1506 clause\&.
1507 .PP
1508 The
1509 INTERSECT
1510 operator computes the set intersection of the rows returned by the involved
1511 \fBSELECT\fR
1512 statements\&. A row is in the intersection of two result sets if it appears in both result sets\&.
1513 .PP
1514 The result of
1515 INTERSECT
1516 does not contain any duplicate rows unless the
1517 ALL
1518 option is specified\&. With
1519 ALL, a row that has
1520 \fIm\fR
1521 duplicates in the left table and
1522 \fIn\fR
1523 duplicates in the right table will appear min(\fIm\fR,\fIn\fR) times in the result set\&.
1524 DISTINCT
1525 can be written to explicitly specify the default behavior of eliminating duplicate rows\&.
1526 .PP
1527 Multiple
1528 INTERSECT
1529 operators in the same
1530 \fBSELECT\fR
1531 statement are evaluated left to right, unless parentheses dictate otherwise\&.
1532 INTERSECT
1533 binds more tightly than
1534 UNION\&. That is,
1535 A UNION B INTERSECT C
1536 will be read as
1537 A UNION (B INTERSECT C)\&.
1538 .PP
1539 Currently,
1540 FOR NO KEY UPDATE,
1541 FOR UPDATE,
1542 FOR SHARE
1543 and
1544 FOR KEY SHARE
1545 cannot be specified either for an
1546 INTERSECT
1547 result or for any input of an
1548 INTERSECT\&.
1549 .SS "EXCEPT Clause"
1550 .PP
1551 The
1552 EXCEPT
1553 clause has this general form:
1554 .sp
1555 .if n \{\
1556 .RS 4
1557 .\}
1558 .nf
1559 \fIselect_statement\fR EXCEPT [ ALL | DISTINCT ] \fIselect_statement\fR
1560 .fi
1561 .if n \{\
1562 .RE
1563 .\}
1564 .sp
1565 \fIselect_statement\fR
1566 is any
1567 \fBSELECT\fR
1568 statement without an
1569 ORDER BY,
1570 LIMIT,
1571 FOR NO KEY UPDATE,
1572 FOR UPDATE,
1573 FOR SHARE, or
1574 FOR KEY SHARE
1575 clause\&.
1576 .PP
1577 The
1578 EXCEPT
1579 operator computes the set of rows that are in the result of the left
1580 \fBSELECT\fR
1581 statement but not in the result of the right one\&.
1582 .PP
1583 The result of
1584 EXCEPT
1585 does not contain any duplicate rows unless the
1586 ALL
1587 option is specified\&. With
1588 ALL, a row that has
1589 \fIm\fR
1590 duplicates in the left table and
1591 \fIn\fR
1592 duplicates in the right table will appear max(\fIm\fR\-\fIn\fR,0) times in the result set\&.
1593 DISTINCT
1594 can be written to explicitly specify the default behavior of eliminating duplicate rows\&.
1595 .PP
1596 Multiple
1597 EXCEPT
1598 operators in the same
1599 \fBSELECT\fR
1600 statement are evaluated left to right, unless parentheses dictate otherwise\&.
1601 EXCEPT
1602 binds at the same level as
1603 UNION\&.
1604 .PP
1605 Currently,
1606 FOR NO KEY UPDATE,
1607 FOR UPDATE,
1608 FOR SHARE
1609 and
1610 FOR KEY SHARE
1611 cannot be specified either for an
1612 EXCEPT
1613 result or for any input of an
1614 EXCEPT\&.
1615 .SS "ORDER BY Clause"
1616 .PP
1617 The optional
1618 ORDER BY
1619 clause has this general form:
1620 .sp
1621 .if n \{\
1622 .RS 4
1623 .\}
1624 .nf
1625 ORDER BY \fIexpression\fR [ ASC | DESC | USING \fIoperator\fR ] [ NULLS { FIRST | LAST } ] [, \&.\&.\&.]
1626 .fi
1627 .if n \{\
1628 .RE
1629 .\}
1630 .sp
1631 The
1632 ORDER BY
1633 clause causes the result rows to be sorted according to the specified expression(s)\&. If two rows are equal according to the leftmost expression, they are compared according to the next expression and so on\&. If they are equal according to all specified expressions, they are returned in an implementation\-dependent order\&.
1634 .PP
1635 Each
1636 \fIexpression\fR
1637 can be the name or ordinal number of an output column (\fBSELECT\fR
1638 list item), or it can be an arbitrary expression formed from input\-column values\&.
1639 .PP
1640 The ordinal number refers to the ordinal (left\-to\-right) position of the output column\&. This feature makes it possible to define an ordering on the basis of a column that does not have a unique name\&. This is never absolutely necessary because it is always possible to assign a name to an output column using the
1641 AS
1642 clause\&.
1643 .PP
1644 It is also possible to use arbitrary expressions in the
1645 ORDER BY
1646 clause, including columns that do not appear in the
1647 \fBSELECT\fR
1648 output list\&. Thus the following statement is valid:
1649 .sp
1650 .if n \{\
1651 .RS 4
1652 .\}
1653 .nf
1654 SELECT name FROM distributors ORDER BY code;
1655 .fi
1656 .if n \{\
1657 .RE
1658 .\}
1659 .sp
1660 A limitation of this feature is that an
1661 ORDER BY
1662 clause applying to the result of a
1663 UNION,
1664 INTERSECT, or
1665 EXCEPT
1666 clause can only specify an output column name or number, not an expression\&.
1667 .PP
1668 If an
1669 ORDER BY
1670 expression is a simple name that matches both an output column name and an input column name,
1671 ORDER BY
1672 will interpret it as the output column name\&. This is the opposite of the choice that
1673 GROUP BY
1674 will make in the same situation\&. This inconsistency is made to be compatible with the SQL standard\&.
1675 .PP
1676 Optionally one can add the key word
1677 ASC
1678 (ascending) or
1679 DESC
1680 (descending) after any expression in the
1681 ORDER BY
1682 clause\&. If not specified,
1683 ASC
1684 is assumed by default\&. Alternatively, a specific ordering operator name can be specified in the
1685 USING
1686 clause\&. An ordering operator must be a less\-than or greater\-than member of some B\-tree operator family\&.
1687 ASC
1688 is usually equivalent to
1689 USING <
1690 and
1691 DESC
1692 is usually equivalent to
1693 USING >\&. (But the creator of a user\-defined data type can define exactly what the default sort ordering is, and it might correspond to operators with other names\&.)
1694 .PP
1695 If
1696 NULLS LAST
1697 is specified, null values sort after all non\-null values; if
1698 NULLS FIRST
1699 is specified, null values sort before all non\-null values\&. If neither is specified, the default behavior is
1700 NULLS LAST
1701 when
1702 ASC
1703 is specified or implied, and
1704 NULLS FIRST
1705 when
1706 DESC
1707 is specified (thus, the default is to act as though nulls are larger than non\-nulls)\&. When
1708 USING
1709 is specified, the default nulls ordering depends on whether the operator is a less\-than or greater\-than operator\&.
1710 .PP
1711 Note that ordering options apply only to the expression they follow; for example
1712 ORDER BY x, y DESC
1713 does not mean the same thing as
1714 ORDER BY x DESC, y DESC\&.
1715 .PP
1716 Character\-string data is sorted according to the collation that applies to the column being sorted\&. That can be overridden at need by including a
1717 COLLATE
1718 clause in the
1719 \fIexpression\fR, for example
1720 ORDER BY mycolumn COLLATE "en_US"\&. For more information see
1721 Section\ \&4.2.10
1722 and
1723 Section\ \&23.2\&.
1724 .SS "LIMIT Clause"
1725 .PP
1726 The
1727 LIMIT
1728 clause consists of two independent sub\-clauses:
1729 .sp
1730 .if n \{\
1731 .RS 4
1732 .\}
1733 .nf
1734 LIMIT { \fIcount\fR | ALL }
1735 OFFSET \fIstart\fR
1736 .fi
1737 .if n \{\
1738 .RE
1739 .\}
1740 .sp
1741 The parameter
1742 \fIcount\fR
1743 specifies the maximum number of rows to return, while
1744 \fIstart\fR
1745 specifies the number of rows to skip before starting to return rows\&. When both are specified,
1746 \fIstart\fR
1747 rows are skipped before starting to count the
1748 \fIcount\fR
1749 rows to be returned\&.
1750 .PP
1751 If the
1752 \fIcount\fR
1753 expression evaluates to NULL, it is treated as
1754 LIMIT ALL, i\&.e\&., no limit\&. If
1755 \fIstart\fR
1756 evaluates to NULL, it is treated the same as
1757 OFFSET 0\&.
1758 .PP
1759 SQL:2008 introduced a different syntax to achieve the same result, which
1760 PostgreSQL
1761 also supports\&. It is:
1762 .sp
1763 .if n \{\
1764 .RS 4
1765 .\}
1766 .nf
1767 OFFSET \fIstart\fR { ROW | ROWS }
1768 FETCH { FIRST | NEXT } [ \fIcount\fR ] { ROW | ROWS } { ONLY | WITH TIES }
1769 .fi
1770 .if n \{\
1771 .RE
1772 .\}
1773 .sp
1774 In this syntax, the
1775 \fIstart\fR
1776 or
1777 \fIcount\fR
1778 value is required by the standard to be a literal constant, a parameter, or a variable name; as a
1779 PostgreSQL
1780 extension, other expressions are allowed, but will generally need to be enclosed in parentheses to avoid ambiguity\&. If
1781 \fIcount\fR
1782 is omitted in a
1783 FETCH
1784 clause, it defaults to 1\&. The
1785 WITH TIES
1786 option is used to return any additional rows that tie for the last place in the result set according to the
1787 ORDER BY
1788 clause;
1789 ORDER BY
1790 is mandatory in this case, and
1791 SKIP LOCKED
1792 is not allowed\&.
1793 ROW
1794 and
1795 ROWS
1796 as well as
1797 FIRST
1798 and
1799 NEXT
1800 are noise words that don\*(Aqt influence the effects of these clauses\&. According to the standard, the
1801 OFFSET
1802 clause must come before the
1803 FETCH
1804 clause if both are present; but
1805 PostgreSQL
1806 is laxer and allows either order\&.
1807 .PP
1808 When using
1809 LIMIT, it is a good idea to use an
1810 ORDER BY
1811 clause that constrains the result rows into a unique order\&. Otherwise you will get an unpredictable subset of the query\*(Aqs rows \(em you might be asking for the tenth through twentieth rows, but tenth through twentieth in what ordering? You don\*(Aqt know what ordering unless you specify
1812 ORDER BY\&.
1813 .PP
1814 The query planner takes
1815 LIMIT
1816 into account when generating a query plan, so you are very likely to get different plans (yielding different row orders) depending on what you use for
1817 LIMIT
1818 and
1819 OFFSET\&. Thus, using different
1820 LIMIT/OFFSET
1821 values to select different subsets of a query result
1822 \fIwill give inconsistent results\fR
1823 unless you enforce a predictable result ordering with
1824 ORDER BY\&. This is not a bug; it is an inherent consequence of the fact that SQL does not promise to deliver the results of a query in any particular order unless
1825 ORDER BY
1826 is used to constrain the order\&.
1827 .PP
1828 It is even possible for repeated executions of the same
1829 LIMIT
1830 query to return different subsets of the rows of a table, if there is not an
1831 ORDER BY
1832 to enforce selection of a deterministic subset\&. Again, this is not a bug; determinism of the results is simply not guaranteed in such a case\&.
1833 .SS "The Locking Clause"
1834 .PP
1835 FOR UPDATE,
1836 FOR NO KEY UPDATE,
1837 FOR SHARE
1838 and
1839 FOR KEY SHARE
1840 are
1841 locking clauses; they affect how
1842 SELECT
1843 locks rows as they are obtained from the table\&.
1844 .PP
1845 The locking clause has the general form
1846 .sp
1847 .if n \{\
1848 .RS 4
1849 .\}
1850 .nf
1851 FOR \fIlock_strength\fR [ OF \fIfrom_reference\fR [, \&.\&.\&.] ] [ NOWAIT | SKIP LOCKED ]
1852 .fi
1853 .if n \{\
1854 .RE
1855 .\}
1856 .sp
1857 where
1858 \fIlock_strength\fR
1859 can be one of
1860 .sp
1861 .if n \{\
1862 .RS 4
1863 .\}
1864 .nf
1865 UPDATE
1866 NO KEY UPDATE
1867 SHARE
1868 KEY SHARE
1869 .fi
1870 .if n \{\
1871 .RE
1872 .\}
1873 .PP
1874 \fIfrom_reference\fR
1875 must be a table
1876 \fIalias\fR
1877 or non\-hidden
1878 \fItable_name\fR
1879 referenced in the
1880 FROM
1881 clause\&. For more information on each row\-level lock mode, refer to
1882 Section\ \&13.3.2\&.
1883 .PP
1884 To prevent the operation from waiting for other transactions to commit, use either the
1885 NOWAIT
1886 or
1887 SKIP LOCKED
1888 option\&. With
1889 NOWAIT, the statement reports an error, rather than waiting, if a selected row cannot be locked immediately\&. With
1890 SKIP LOCKED, any selected rows that cannot be immediately locked are skipped\&. Skipping locked rows provides an inconsistent view of the data, so this is not suitable for general purpose work, but can be used to avoid lock contention with multiple consumers accessing a queue\-like table\&. Note that
1891 NOWAIT
1892 and
1893 SKIP LOCKED
1894 apply only to the row\-level lock(s) \(em the required
1895 ROW SHARE
1896 table\-level lock is still taken in the ordinary way (see
1897 Chapter\ \&13)\&. You can use
1898 \fBLOCK\fR
1899 with the
1900 NOWAIT
1901 option first, if you need to acquire the table\-level lock without waiting\&.
1902 .PP
1903 If specific tables are named in a locking clause, then only rows coming from those tables are locked; any other tables used in the
1904 \fBSELECT\fR
1905 are simply read as usual\&. A locking clause without a table list affects all tables used in the statement\&. If a locking clause is applied to a view or sub\-query, it affects all tables used in the view or sub\-query\&. However, these clauses do not apply to
1906 WITH
1907 queries referenced by the primary query\&. If you want row locking to occur within a
1908 WITH
1909 query, specify a locking clause within the
1910 WITH
1911 query\&.
1912 .PP
1913 Multiple locking clauses can be written if it is necessary to specify different locking behavior for different tables\&. If the same table is mentioned (or implicitly affected) by more than one locking clause, then it is processed as if it was only specified by the strongest one\&. Similarly, a table is processed as
1914 NOWAIT
1915 if that is specified in any of the clauses affecting it\&. Otherwise, it is processed as
1916 SKIP LOCKED
1917 if that is specified in any of the clauses affecting it\&.
1918 .PP
1919 The locking clauses cannot be used in contexts where returned rows cannot be clearly identified with individual table rows; for example they cannot be used with aggregation\&.
1920 .PP
1921 When a locking clause appears at the top level of a
1922 \fBSELECT\fR
1923 query, the rows that are locked are exactly those that are returned by the query; in the case of a join query, the rows locked are those that contribute to returned join rows\&. In addition, rows that satisfied the query conditions as of the query snapshot will be locked, although they will not be returned if they were updated after the snapshot and no longer satisfy the query conditions\&. If a
1924 LIMIT
1925 is used, locking stops once enough rows have been returned to satisfy the limit (but note that rows skipped over by
1926 OFFSET
1927 will get locked)\&. Similarly, if a locking clause is used in a cursor\*(Aqs query, only rows actually fetched or stepped past by the cursor will be locked\&.
1928 .PP
1929 When a locking clause appears in a sub\-\fBSELECT\fR, the rows locked are those returned to the outer query by the sub\-query\&. This might involve fewer rows than inspection of the sub\-query alone would suggest, since conditions from the outer query might be used to optimize execution of the sub\-query\&. For example,
1930 .sp
1931 .if n \{\
1932 .RS 4
1933 .\}
1934 .nf
1935 SELECT * FROM (SELECT * FROM mytable FOR UPDATE) ss WHERE col1 = 5;
1936 .fi
1937 .if n \{\
1938 .RE
1939 .\}
1940 .sp
1941 will lock only rows having
1942 col1 = 5, even though that condition is not textually within the sub\-query\&.
1943 .PP
1944 Previous releases failed to preserve a lock which is upgraded by a later savepoint\&. For example, this code:
1945 .sp
1946 .if n \{\
1947 .RS 4
1948 .\}
1949 .nf
1950 BEGIN;
1951 SELECT * FROM mytable WHERE key = 1 FOR UPDATE;
1952 SAVEPOINT s;
1953 UPDATE mytable SET \&.\&.\&. WHERE key = 1;
1954 ROLLBACK TO s;
1955 .fi
1956 .if n \{\
1957 .RE
1958 .\}
1959 .sp
1960 would fail to preserve the
1961 FOR UPDATE
1962 lock after the
1963 \fBROLLBACK TO\fR\&. This has been fixed in release 9\&.3\&.
1964 .if n \{\
1965 .sp
1966 .\}
1967 .RS 4
1968 .it 1 an-trap
1969 .nr an-no-space-flag 1
1970 .nr an-break-flag 1
1971 .br
1972 .ps +1
1973 \fBCaution\fR
1974 .ps -1
1975 .br
1976 .PP
1977 It is possible for a
1978 \fBSELECT\fR
1979 command running at the
1980 READ COMMITTED
1981 transaction isolation level and using
1982 ORDER BY
1983 and a locking clause to return rows out of order\&. This is because
1984 ORDER BY
1985 is applied first\&. The command sorts the result, but might then block trying to obtain a lock on one or more of the rows\&. Once the
1986 SELECT
1987 unblocks, some of the ordering column values might have been modified, leading to those rows appearing to be out of order (though they are in order in terms of the original column values)\&. This can be worked around at need by placing the
1988 FOR UPDATE/SHARE
1989 clause in a sub\-query, for example
1990 .sp
1991 .if n \{\
1992 .RS 4
1993 .\}
1994 .nf
1995 SELECT * FROM (SELECT * FROM mytable FOR UPDATE) ss ORDER BY column1;
1996 .fi
1997 .if n \{\
1998 .RE
1999 .\}
2000 .sp
2001 Note that this will result in locking all rows of
2002 mytable, whereas
2003 FOR UPDATE
2004 at the top level would lock only the actually returned rows\&. This can make for a significant performance difference, particularly if the
2005 ORDER BY
2006 is combined with
2007 LIMIT
2008 or other restrictions\&. So this technique is recommended only if concurrent updates of the ordering columns are expected and a strictly sorted result is required\&.
2009 .PP
2010 At the
2011 REPEATABLE READ
2012 or
2013 SERIALIZABLE
2014 transaction isolation level this would cause a serialization failure (with an
2015 SQLSTATE
2016 of
2017 \*(Aq40001\*(Aq), so there is no possibility of receiving rows out of order under these isolation levels\&.
2018 .sp .5v
2019 .RE
2020 .SS "TABLE Command"
2021 .PP
2022 The command
2023 .sp
2024 .if n \{\
2025 .RS 4
2026 .\}
2027 .nf
2028 TABLE \fIname\fR
2029 .fi
2030 .if n \{\
2031 .RE
2032 .\}
2033 .sp
2034 is equivalent to
2035 .sp
2036 .if n \{\
2037 .RS 4
2038 .\}
2039 .nf
2040 SELECT * FROM \fIname\fR
2041 .fi
2042 .if n \{\
2043 .RE
2044 .\}
2045 .sp
2046 It can be used as a top\-level command or as a space\-saving syntax variant in parts of complex queries\&. Only the
2047 WITH,
2048 UNION,
2049 INTERSECT,
2050 EXCEPT,
2051 ORDER BY,
2052 LIMIT,
2053 OFFSET,
2054 FETCH
2055 and
2056 FOR
2057 locking clauses can be used with
2058 \fBTABLE\fR; the
2059 WHERE
2060 clause and any form of aggregation cannot be used\&.
2061 .SH "EXAMPLES"
2062 .PP
2063 To join the table
2064 films
2065 with the table
2066 distributors:
2067 .sp
2068 .if n \{\
2069 .RS 4
2070 .\}
2071 .nf
2072 SELECT f\&.title, f\&.did, d\&.name, f\&.date_prod, f\&.kind
2073     FROM distributors d JOIN films f USING (did);
2074
2075        title       | did |     name     | date_prod  |   kind
2076 \-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-
2077  The Third Man     | 101 | British Lion | 1949\-12\-23 | Drama
2078  The African Queen | 101 | British Lion | 1951\-08\-11 | Romantic
2079  \&.\&.\&.
2080 .fi
2081 .if n \{\
2082 .RE
2083 .\}
2084 .PP
2085 To sum the column
2086 len
2087 of all films and group the results by
2088 kind:
2089 .sp
2090 .if n \{\
2091 .RS 4
2092 .\}
2093 .nf
2094 SELECT kind, sum(len) AS total FROM films GROUP BY kind;
2095
2096    kind   | total
2097 \-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-
2098  Action   | 07:34
2099  Comedy   | 02:58
2100  Drama    | 14:28
2101  Musical  | 06:42
2102  Romantic | 04:38
2103 .fi
2104 .if n \{\
2105 .RE
2106 .\}
2107 .PP
2108 To sum the column
2109 len
2110 of all films, group the results by
2111 kind
2112 and show those group totals that are less than 5 hours:
2113 .sp
2114 .if n \{\
2115 .RS 4
2116 .\}
2117 .nf
2118 SELECT kind, sum(len) AS total
2119     FROM films
2120     GROUP BY kind
2121     HAVING sum(len) < interval \*(Aq5 hours\*(Aq;
2122
2123    kind   | total
2124 \-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-
2125  Comedy   | 02:58
2126  Romantic | 04:38
2127 .fi
2128 .if n \{\
2129 .RE
2130 .\}
2131 .PP
2132 The following two examples are identical ways of sorting the individual results according to the contents of the second column (name):
2133 .sp
2134 .if n \{\
2135 .RS 4
2136 .\}
2137 .nf
2138 SELECT * FROM distributors ORDER BY name;
2139 SELECT * FROM distributors ORDER BY 2;
2140
2141  did |       name
2142 \-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
2143  109 | 20th Century Fox
2144  110 | Bavaria Atelier
2145  101 | British Lion
2146  107 | Columbia
2147  102 | Jean Luc Godard
2148  113 | Luso films
2149  104 | Mosfilm
2150  103 | Paramount
2151  106 | Toho
2152  105 | United Artists
2153  111 | Walt Disney
2154  112 | Warner Bros\&.
2155  108 | Westward
2156 .fi
2157 .if n \{\
2158 .RE
2159 .\}
2160 .PP
2161 The next example shows how to obtain the union of the tables
2162 distributors
2163 and
2164 actors, restricting the results to those that begin with the letter W in each table\&. Only distinct rows are wanted, so the key word
2165 ALL
2166 is omitted\&.
2167 .sp
2168 .if n \{\
2169 .RS 4
2170 .\}
2171 .nf
2172 distributors:               actors:
2173  did |     name              id |     name
2174 \-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-        \-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
2175  108 | Westward               1 | Woody Allen
2176  111 | Walt Disney            2 | Warren Beatty
2177  112 | Warner Bros\&.           3 | Walter Matthau
2178  \&.\&.\&.                         \&.\&.\&.
2179
2180 SELECT distributors\&.name
2181     FROM distributors
2182     WHERE distributors\&.name LIKE \*(AqW%\*(Aq
2183 UNION
2184 SELECT actors\&.name
2185     FROM actors
2186     WHERE actors\&.name LIKE \*(AqW%\*(Aq;
2187
2188       name
2189 \-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
2190  Walt Disney
2191  Walter Matthau
2192  Warner Bros\&.
2193  Warren Beatty
2194  Westward
2195  Woody Allen
2196 .fi
2197 .if n \{\
2198 .RE
2199 .\}
2200 .PP
2201 This example shows how to use a function in the
2202 FROM
2203 clause, both with and without a column definition list:
2204 .sp
2205 .if n \{\
2206 .RS 4
2207 .\}
2208 .nf
2209 CREATE FUNCTION distributors(int) RETURNS SETOF distributors AS $$
2210     SELECT * FROM distributors WHERE did = $1;
2211 $$ LANGUAGE SQL;
2212
2213 SELECT * FROM distributors(111);
2214  did |    name
2215 \-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-
2216  111 | Walt Disney
2217
2218 CREATE FUNCTION distributors_2(int) RETURNS SETOF record AS $$
2219     SELECT * FROM distributors WHERE did = $1;
2220 $$ LANGUAGE SQL;
2221
2222 SELECT * FROM distributors_2(111) AS (f1 int, f2 text);
2223  f1  |     f2
2224 \-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-
2225  111 | Walt Disney
2226 .fi
2227 .if n \{\
2228 .RE
2229 .\}
2230 .PP
2231 Here is an example of a function with an ordinality column added:
2232 .sp
2233 .if n \{\
2234 .RS 4
2235 .\}
2236 .nf
2237 SELECT * FROM unnest(ARRAY[\*(Aqa\*(Aq,\*(Aqb\*(Aq,\*(Aqc\*(Aq,\*(Aqd\*(Aq,\*(Aqe\*(Aq,\*(Aqf\*(Aq]) WITH ORDINALITY;
2238  unnest | ordinality
2239 \-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-
2240  a      |        1
2241  b      |        2
2242  c      |        3
2243  d      |        4
2244  e      |        5
2245  f      |        6
2246 (6 rows)
2247 .fi
2248 .if n \{\
2249 .RE
2250 .\}
2251 .PP
2252 This example shows how to use a simple
2253 WITH
2254 clause:
2255 .sp
2256 .if n \{\
2257 .RS 4
2258 .\}
2259 .nf
2260 WITH t AS (
2261     SELECT random() as x FROM generate_series(1, 3)
2262   )
2263 SELECT * FROM t
2264 UNION ALL
2265 SELECT * FROM t;
2266          x
2267 \-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
2268   0\&.534150459803641
2269   0\&.520092216785997
2270  0\&.0735620250925422
2271   0\&.534150459803641
2272   0\&.520092216785997
2273  0\&.0735620250925422
2274 .fi
2275 .if n \{\
2276 .RE
2277 .\}
2278 .sp
2279 Notice that the
2280 WITH
2281 query was evaluated only once, so that we got two sets of the same three random values\&.
2282 .PP
2283 This example uses
2284 WITH RECURSIVE
2285 to find all subordinates (direct or indirect) of the employee Mary, and their level of indirectness, from a table that shows only direct subordinates:
2286 .sp
2287 .if n \{\
2288 .RS 4
2289 .\}
2290 .nf
2291 WITH RECURSIVE employee_recursive(distance, employee_name, manager_name) AS (
2292     SELECT 1, employee_name, manager_name
2293     FROM employee
2294     WHERE manager_name = \*(AqMary\*(Aq
2295   UNION ALL
2296     SELECT er\&.distance + 1, e\&.employee_name, e\&.manager_name
2297     FROM employee_recursive er, employee e
2298     WHERE er\&.employee_name = e\&.manager_name
2299   )
2300 SELECT distance, employee_name FROM employee_recursive;
2301 .fi
2302 .if n \{\
2303 .RE
2304 .\}
2305 .sp
2306 Notice the typical form of recursive queries: an initial condition, followed by
2307 UNION, followed by the recursive part of the query\&. Be sure that the recursive part of the query will eventually return no tuples, or else the query will loop indefinitely\&. (See
2308 Section\ \&7.8
2309 for more examples\&.)
2310 .PP
2311 This example uses
2312 LATERAL
2313 to apply a set\-returning function
2314 \fBget_product_names()\fR
2315 for each row of the
2316 manufacturers
2317 table:
2318 .sp
2319 .if n \{\
2320 .RS 4
2321 .\}
2322 .nf
2323 SELECT m\&.name AS mname, pname
2324 FROM manufacturers m, LATERAL get_product_names(m\&.id) pname;
2325 .fi
2326 .if n \{\
2327 .RE
2328 .\}
2329 .sp
2330 Manufacturers not currently having any products would not appear in the result, since it is an inner join\&. If we wished to include the names of such manufacturers in the result, we could do:
2331 .sp
2332 .if n \{\
2333 .RS 4
2334 .\}
2335 .nf
2336 SELECT m\&.name AS mname, pname
2337 FROM manufacturers m LEFT JOIN LATERAL get_product_names(m\&.id) pname ON true;
2338 .fi
2339 .if n \{\
2340 .RE
2341 .\}
2342 .SH "COMPATIBILITY"
2343 .PP
2344 Of course, the
2345 \fBSELECT\fR
2346 statement is compatible with the SQL standard\&. But there are some extensions and some missing features\&.
2347 .SS "Omitted FROM Clauses"
2348 .PP
2349 PostgreSQL
2350 allows one to omit the
2351 FROM
2352 clause\&. It has a straightforward use to compute the results of simple expressions:
2353 .sp
2354 .if n \{\
2355 .RS 4
2356 .\}
2357 .nf
2358 SELECT 2+2;
2359
2360  ?column?
2361 \-\-\-\-\-\-\-\-\-\-
2362         4
2363 .fi
2364 .if n \{\
2365 .RE
2366 .\}
2367 .sp
2368 Some other
2369 SQL
2370 databases cannot do this except by introducing a dummy one\-row table from which to do the
2371 \fBSELECT\fR\&.
2372 .SS "Empty SELECT Lists"
2373 .PP
2374 The list of output expressions after
2375 SELECT
2376 can be empty, producing a zero\-column result table\&. This is not valid syntax according to the SQL standard\&.
2377 PostgreSQL
2378 allows it to be consistent with allowing zero\-column tables\&. However, an empty list is not allowed when
2379 DISTINCT
2380 is used\&.
2381 .SS "Omitting the AS Key Word"
2382 .PP
2383 In the SQL standard, the optional key word
2384 AS
2385 can be omitted before an output column name whenever the new column name is a valid column name (that is, not the same as any reserved keyword)\&.
2386 PostgreSQL
2387 is slightly more restrictive:
2388 AS
2389 is required if the new column name matches any keyword at all, reserved or not\&. Recommended practice is to use
2390 AS
2391 or double\-quote output column names, to prevent any possible conflict against future keyword additions\&.
2392 .PP
2393 In
2394 FROM
2395 items, both the standard and
2396 PostgreSQL
2397 allow
2398 AS
2399 to be omitted before an alias that is an unreserved keyword\&. But this is impractical for output column names, because of syntactic ambiguities\&.
2400 .SS "Omitting Sub\-SELECT Aliases in FROM"
2401 .PP
2402 According to the SQL standard, a sub\-\fBSELECT\fR
2403 in the
2404 FROM
2405 list must have an alias\&. In
2406 PostgreSQL, this alias may be omitted\&.
2407 .SS "ONLY and Inheritance"
2408 .PP
2409 The SQL standard requires parentheses around the table name when writing
2410 ONLY, for example
2411 SELECT * FROM ONLY (tab1), ONLY (tab2) WHERE \&.\&.\&.\&.
2412 PostgreSQL
2413 considers these parentheses to be optional\&.
2414 .PP
2415 PostgreSQL
2416 allows a trailing
2417 *
2418 to be written to explicitly specify the non\-ONLY
2419 behavior of including child tables\&. The standard does not allow this\&.
2420 .PP
2421 (These points apply equally to all SQL commands supporting the
2422 ONLY
2423 option\&.)
2424 .SS "TABLESAMPLE Clause Restrictions"
2425 .PP
2426 The
2427 TABLESAMPLE
2428 clause is currently accepted only on regular tables and materialized views\&. According to the SQL standard it should be possible to apply it to any
2429 FROM
2430 item\&.
2431 .SS "Function Calls in FROM"
2432 .PP
2433 PostgreSQL
2434 allows a function call to be written directly as a member of the
2435 FROM
2436 list\&. In the SQL standard it would be necessary to wrap such a function call in a sub\-\fBSELECT\fR; that is, the syntax
2437 FROM \fIfunc\fR(\&.\&.\&.) \fIalias\fR
2438 is approximately equivalent to
2439 FROM LATERAL (SELECT \fIfunc\fR(\&.\&.\&.)) \fIalias\fR\&. Note that
2440 LATERAL
2441 is considered to be implicit; this is because the standard requires
2442 LATERAL
2443 semantics for an
2444 UNNEST()
2445 item in
2446 FROM\&.
2447 PostgreSQL
2448 treats
2449 UNNEST()
2450 the same as other set\-returning functions\&.
2451 .SS "Namespace Available to GROUP BY and ORDER BY"
2452 .PP
2453 In the SQL\-92 standard, an
2454 ORDER BY
2455 clause can only use output column names or numbers, while a
2456 GROUP BY
2457 clause can only use expressions based on input column names\&.
2458 PostgreSQL
2459 extends each of these clauses to allow the other choice as well (but it uses the standard\*(Aqs interpretation if there is ambiguity)\&.
2460 PostgreSQL
2461 also allows both clauses to specify arbitrary expressions\&. Note that names appearing in an expression will always be taken as input\-column names, not as output\-column names\&.
2462 .PP
2463 SQL:1999 and later use a slightly different definition which is not entirely upward compatible with SQL\-92\&. In most cases, however,
2464 PostgreSQL
2465 will interpret an
2466 ORDER BY
2467 or
2468 GROUP BY
2469 expression the same way SQL:1999 does\&.
2470 .SS "Functional Dependencies"
2471 .PP
2472 PostgreSQL
2473 recognizes functional dependency (allowing columns to be omitted from
2474 GROUP BY) only when a table\*(Aqs primary key is included in the
2475 GROUP BY
2476 list\&. The SQL standard specifies additional conditions that should be recognized\&.
2477 .SS "LIMIT and OFFSET"
2478 .PP
2479 The clauses
2480 LIMIT
2481 and
2482 OFFSET
2483 are
2484 PostgreSQL\-specific syntax, also used by
2485 MySQL\&. The SQL:2008 standard has introduced the clauses
2486 OFFSET \&.\&.\&. FETCH {FIRST|NEXT} \&.\&.\&.
2487 for the same functionality, as shown above in
2488 LIMIT Clause\&. This syntax is also used by
2489 IBM DB2\&. (Applications written for
2490 Oracle
2491 frequently use a workaround involving the automatically generated
2492 rownum
2493 column, which is not available in PostgreSQL, to implement the effects of these clauses\&.)
2494 .SS "FOR NO KEY UPDATE, FOR UPDATE, FOR SHARE, FOR KEY SHARE"
2495 .PP
2496 Although
2497 FOR UPDATE
2498 appears in the SQL standard, the standard allows it only as an option of
2499 \fBDECLARE CURSOR\fR\&.
2500 PostgreSQL
2501 allows it in any
2502 \fBSELECT\fR
2503 query as well as in sub\-\fBSELECT\fRs, but this is an extension\&. The
2504 FOR NO KEY UPDATE,
2505 FOR SHARE
2506 and
2507 FOR KEY SHARE
2508 variants, as well as the
2509 NOWAIT
2510 and
2511 SKIP LOCKED
2512 options, do not appear in the standard\&.
2513 .SS "Data\-Modifying Statements in WITH"
2514 .PP
2515 PostgreSQL
2516 allows
2517 \fBINSERT\fR,
2518 \fBUPDATE\fR,
2519 \fBDELETE\fR, and
2520 \fBMERGE\fR
2521 to be used as
2522 WITH
2523 queries\&. This is not found in the SQL standard\&.
2524 .SS "Nonstandard Clauses"
2525 .PP
2526 DISTINCT ON ( \&.\&.\&. )
2527 is an extension of the SQL standard\&.
2528 .PP
2529 ROWS FROM( \&.\&.\&. )
2530 is an extension of the SQL standard\&.
2531 .PP
2532 The
2533 MATERIALIZED
2534 and
2535 NOT MATERIALIZED
2536 options of
2537 WITH
2538 are extensions of the SQL standard\&.