summaryrefslogtreecommitdiffstats
path: root/doc/src/sgml/man7/SELECT.7
blob: 8f0157c038537d6503218660c6d29dd11c5f93f5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
'\" t
.\"     Title: SELECT
.\"    Author: The PostgreSQL Global Development Group
.\" Generator: DocBook XSL Stylesheets vsnapshot <http://docbook.sf.net/>
.\"      Date: 2024
.\"    Manual: PostgreSQL 15.7 Documentation
.\"    Source: PostgreSQL 15.7
.\"  Language: English
.\"
.TH "SELECT" "7" "2024" "PostgreSQL 15.7" "PostgreSQL 15.7 Documentation"
.\" -----------------------------------------------------------------
.\" * Define some portability stuff
.\" -----------------------------------------------------------------
.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.\" http://bugs.debian.org/507673
.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html
.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.ie \n(.g .ds Aq \(aq
.el       .ds Aq '
.\" -----------------------------------------------------------------
.\" * set default formatting
.\" -----------------------------------------------------------------
.\" disable hyphenation
.nh
.\" disable justification (adjust text to left margin only)
.ad l
.\" -----------------------------------------------------------------
.\" * MAIN CONTENT STARTS HERE *
.\" -----------------------------------------------------------------
.SH "NAME"
SELECT, TABLE, WITH \- retrieve rows from a table or view
.SH "SYNOPSIS"
.sp
.nf
[ WITH [ RECURSIVE ] \fIwith_query\fR [, \&.\&.\&.] ]
SELECT [ ALL | DISTINCT [ ON ( \fIexpression\fR [, \&.\&.\&.] ) ] ]
    [ * | \fIexpression\fR [ [ AS ] \fIoutput_name\fR ] [, \&.\&.\&.] ]
    [ FROM \fIfrom_item\fR [, \&.\&.\&.] ]
    [ WHERE \fIcondition\fR ]
    [ GROUP BY [ ALL | DISTINCT ] \fIgrouping_element\fR [, \&.\&.\&.] ]
    [ HAVING \fIcondition\fR ]
    [ WINDOW \fIwindow_name\fR AS ( \fIwindow_definition\fR ) [, \&.\&.\&.] ]
    [ { UNION | INTERSECT | EXCEPT } [ ALL | DISTINCT ] \fIselect\fR ]
    [ ORDER BY \fIexpression\fR [ ASC | DESC | USING \fIoperator\fR ] [ NULLS { FIRST | LAST } ] [, \&.\&.\&.] ]
    [ LIMIT { \fIcount\fR | ALL } ]
    [ OFFSET \fIstart\fR [ ROW | ROWS ] ]
    [ FETCH { FIRST | NEXT } [ \fIcount\fR ] { ROW | ROWS } { ONLY | WITH TIES } ]
    [ FOR { UPDATE | NO KEY UPDATE | SHARE | KEY SHARE } [ OF \fItable_name\fR [, \&.\&.\&.] ] [ NOWAIT | SKIP LOCKED ] [\&.\&.\&.] ]

where \fIfrom_item\fR can be one of:

    [ ONLY ] \fItable_name\fR [ * ] [ [ AS ] \fIalias\fR [ ( \fIcolumn_alias\fR [, \&.\&.\&.] ) ] ]
                [ TABLESAMPLE \fIsampling_method\fR ( \fIargument\fR [, \&.\&.\&.] ) [ REPEATABLE ( \fIseed\fR ) ] ]
    [ LATERAL ] ( \fIselect\fR ) [ AS ] \fIalias\fR [ ( \fIcolumn_alias\fR [, \&.\&.\&.] ) ]
    \fIwith_query_name\fR [ [ AS ] \fIalias\fR [ ( \fIcolumn_alias\fR [, \&.\&.\&.] ) ] ]
    [ LATERAL ] \fIfunction_name\fR ( [ \fIargument\fR [, \&.\&.\&.] ] )
                [ WITH ORDINALITY ] [ [ AS ] \fIalias\fR [ ( \fIcolumn_alias\fR [, \&.\&.\&.] ) ] ]
    [ LATERAL ] \fIfunction_name\fR ( [ \fIargument\fR [, \&.\&.\&.] ] ) [ AS ] \fIalias\fR ( \fIcolumn_definition\fR [, \&.\&.\&.] )
    [ LATERAL ] \fIfunction_name\fR ( [ \fIargument\fR [, \&.\&.\&.] ] ) AS ( \fIcolumn_definition\fR [, \&.\&.\&.] )
    [ LATERAL ] ROWS FROM( \fIfunction_name\fR ( [ \fIargument\fR [, \&.\&.\&.] ] ) [ AS ( \fIcolumn_definition\fR [, \&.\&.\&.] ) ] [, \&.\&.\&.] )
                [ WITH ORDINALITY ] [ [ AS ] \fIalias\fR [ ( \fIcolumn_alias\fR [, \&.\&.\&.] ) ] ]
    \fIfrom_item\fR \fIjoin_type\fR \fIfrom_item\fR { ON \fIjoin_condition\fR | USING ( \fIjoin_column\fR [, \&.\&.\&.] ) [ AS \fIjoin_using_alias\fR ] }
    \fIfrom_item\fR NATURAL \fIjoin_type\fR \fIfrom_item\fR
    \fIfrom_item\fR CROSS JOIN \fIfrom_item\fR

and \fIgrouping_element\fR can be one of:

    ( )
    \fIexpression\fR
    ( \fIexpression\fR [, \&.\&.\&.] )
    ROLLUP ( { \fIexpression\fR | ( \fIexpression\fR [, \&.\&.\&.] ) } [, \&.\&.\&.] )
    CUBE ( { \fIexpression\fR | ( \fIexpression\fR [, \&.\&.\&.] ) } [, \&.\&.\&.] )
    GROUPING SETS ( \fIgrouping_element\fR [, \&.\&.\&.] )

and \fIwith_query\fR is:

    \fIwith_query_name\fR [ ( \fIcolumn_name\fR [, \&.\&.\&.] ) ] AS [ [ NOT ] MATERIALIZED ] ( \fIselect\fR | \fIvalues\fR | \fIinsert\fR | \fIupdate\fR | \fIdelete\fR )
        [ SEARCH { BREADTH | DEPTH } FIRST BY \fIcolumn_name\fR [, \&.\&.\&.] SET \fIsearch_seq_col_name\fR ]
        [ 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 ]

TABLE [ ONLY ] \fItable_name\fR [ * ]
.fi
.SH "DESCRIPTION"
.PP
\fBSELECT\fR
retrieves rows from zero or more tables\&. The general processing of
\fBSELECT\fR
is as follows:
.sp
.RS 4
.ie n \{\
\h'-04' 1.\h'+01'\c
.\}
.el \{\
.sp -1
.IP "  1." 4.2
.\}
All queries in the
WITH
list are computed\&. These effectively serve as temporary tables that can be referenced in the
FROM
list\&. A
WITH
query that is referenced more than once in
FROM
is computed only once, unless specified otherwise with
NOT MATERIALIZED\&. (See
WITH Clause
below\&.)
.RE
.sp
.RS 4
.ie n \{\
\h'-04' 2.\h'+01'\c
.\}
.el \{\
.sp -1
.IP "  2." 4.2
.\}
All elements in the
FROM
list are computed\&. (Each element in the
FROM
list is a real or virtual table\&.) If more than one element is specified in the
FROM
list, they are cross\-joined together\&. (See
FROM Clause
below\&.)
.RE
.sp
.RS 4
.ie n \{\
\h'-04' 3.\h'+01'\c
.\}
.el \{\
.sp -1
.IP "  3." 4.2
.\}
If the
WHERE
clause is specified, all rows that do not satisfy the condition are eliminated from the output\&. (See
WHERE Clause
below\&.)
.RE
.sp
.RS 4
.ie n \{\
\h'-04' 4.\h'+01'\c
.\}
.el \{\
.sp -1
.IP "  4." 4.2
.\}
If the
GROUP BY
clause is specified, or if there are aggregate function calls, the output is combined into groups of rows that match on one or more values, and the results of aggregate functions are computed\&. If the
HAVING
clause is present, it eliminates groups that do not satisfy the given condition\&. (See
GROUP BY Clause
and
HAVING Clause
below\&.) Although query output columns are nominally computed in the next step, they can also be referenced (by name or ordinal number) in the
GROUP BY
clause\&.
.RE
.sp
.RS 4
.ie n \{\
\h'-04' 5.\h'+01'\c
.\}
.el \{\
.sp -1
.IP "  5." 4.2
.\}
The actual output rows are computed using the
\fBSELECT\fR
output expressions for each selected row or row group\&. (See
SELECT List
below\&.)
.RE
.sp
.RS 4
.ie n \{\
\h'-04' 6.\h'+01'\c
.\}
.el \{\
.sp -1
.IP "  6." 4.2
.\}
SELECT DISTINCT
eliminates duplicate rows from the result\&.
SELECT DISTINCT ON
eliminates rows that match on all the specified expressions\&.
SELECT ALL
(the default) will return all candidate rows, including duplicates\&. (See
DISTINCT Clause
below\&.)
.RE
.sp
.RS 4
.ie n \{\
\h'-04' 7.\h'+01'\c
.\}
.el \{\
.sp -1
.IP "  7." 4.2
.\}
Using the operators
UNION,
INTERSECT, and
EXCEPT, the output of more than one
\fBSELECT\fR
statement can be combined to form a single result set\&. The
UNION
operator returns all rows that are in one or both of the result sets\&. The
INTERSECT
operator returns all rows that are strictly in both result sets\&. The
EXCEPT
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
ALL
is specified\&. The noise word
DISTINCT
can be added to explicitly specify eliminating duplicate rows\&. Notice that
DISTINCT
is the default behavior here, even though
ALL
is the default for
\fBSELECT\fR
itself\&. (See
UNION Clause,
INTERSECT Clause, and
EXCEPT Clause
below\&.)
.RE
.sp
.RS 4
.ie n \{\
\h'-04' 8.\h'+01'\c
.\}
.el \{\
.sp -1
.IP "  8." 4.2
.\}
If the
ORDER BY
clause is specified, the returned rows are sorted in the specified order\&. If
ORDER BY
is not given, the rows are returned in whatever order the system finds fastest to produce\&. (See
ORDER BY Clause
below\&.)
.RE
.sp
.RS 4
.ie n \{\
\h'-04' 9.\h'+01'\c
.\}
.el \{\
.sp -1
.IP "  9." 4.2
.\}
If the
LIMIT
(or
FETCH FIRST) or
OFFSET
clause is specified, the
\fBSELECT\fR
statement only returns a subset of the result rows\&. (See
LIMIT Clause
below\&.)
.RE
.sp
.RS 4
.ie n \{\
\h'-04'10.\h'+01'\c
.\}
.el \{\
.sp -1
.IP "10." 4.2
.\}
If
FOR UPDATE,
FOR NO KEY UPDATE,
FOR SHARE
or
FOR KEY SHARE
is specified, the
\fBSELECT\fR
statement locks the selected rows against concurrent updates\&. (See
The Locking Clause
below\&.)
.RE
.PP
You must have
SELECT
privilege on each column used in a
\fBSELECT\fR
command\&. The use of
FOR NO KEY UPDATE,
FOR UPDATE,
FOR SHARE
or
FOR KEY SHARE
requires
UPDATE
privilege as well (for at least one column of each table so selected)\&.
.SH "PARAMETERS"
.SS "WITH Clause"
.PP
The
WITH
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
\fBSELECT\fR,
\fBTABLE\fR,
\fBVALUES\fR,
\fBINSERT\fR,
\fBUPDATE\fR
or
\fBDELETE\fR
statement\&. When writing a data\-modifying statement (\fBINSERT\fR,
\fBUPDATE\fR
or
\fBDELETE\fR) in
WITH, it is usual to include a
RETURNING
clause\&. It is the output of
RETURNING,
\fInot\fR
the underlying table that the statement modifies, that forms the temporary table that is read by the primary query\&. If
RETURNING
is omitted, the statement is still executed, but it produces no output so it cannot be referenced as a table by the primary query\&.
.PP
A name (without schema qualification) must be specified for each
WITH
query\&. Optionally, a list of column names can be specified; if this is omitted, the column names are inferred from the subquery\&.
.PP
If
RECURSIVE
is specified, it allows a
\fBSELECT\fR
subquery to reference itself by name\&. Such a subquery must have the form
.sp
.if n \{\
.RS 4
.\}
.nf
\fInon_recursive_term\fR UNION [ ALL | DISTINCT ] \fIrecursive_term\fR
.fi
.if n \{\
.RE
.\}
.sp
where the recursive self\-reference must appear on the right\-hand side of the
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
\fBSELECT\fR
query in a data\-modifying statement\&. See
Section\ \&7.8
for an example\&.
.PP
Another effect of
RECURSIVE
is that
WITH
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
RECURSIVE,
WITH
queries can only reference sibling
WITH
queries that are earlier in the
WITH
list\&.
.PP
When there are multiple queries in the
WITH
clause,
RECURSIVE
should be written only once, immediately after
WITH\&. It applies to all queries in the
WITH
clause, though it has no effect on queries that do not use recursion or forward references\&.
.PP
The optional
SEARCH
clause computes a
search sequence column
that can be used for ordering the results of a recursive query in either breadth\-first or depth\-first order\&. The supplied column name list specifies the row key that is to be used for keeping track of visited rows\&. A column named
\fIsearch_seq_col_name\fR
will be added to the result column list of the
WITH
query\&. This column can be ordered by in the outer query to achieve the respective ordering\&. See
Section\ \&7.8.2.1
for examples\&.
.PP
The optional
CYCLE
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
\fIcycle_mark_col_name\fR
will be added to the result column list of the
WITH
query\&. This column will be set to
\fIcycle_mark_value\fR
when a cycle has been detected, else to
\fIcycle_mark_default\fR\&. Furthermore, processing of the recursive union will stop when a cycle has been detected\&.
\fIcycle_mark_value\fR
and
\fIcycle_mark_default\fR
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,
TRUE
and
FALSE
(of type
boolean) are used\&. Furthermore, a column named
\fIcycle_path_col_name\fR
will be added to the result column list of the
WITH
query\&. This column is used internally for tracking visited rows\&. See
Section\ \&7.8.2.2
for examples\&.
.PP
Both the
SEARCH
and the
CYCLE
clause are only valid for recursive
WITH
queries\&. The
\fIwith_query\fR
must be a
UNION
(or
UNION ALL) of two
SELECT
(or equivalent) commands (no nested
UNIONs)\&. If both clauses are used, the column added by the
SEARCH
clause appears before the columns added by the
CYCLE
clause\&.
.PP
The primary query and the
WITH
queries are all (notionally) executed at the same time\&. This implies that the effects of a data\-modifying statement in
WITH
cannot be seen from other parts of the query, other than by reading its
RETURNING
output\&. If two such data\-modifying statements attempt to modify the same row, the results are unspecified\&.
.PP
A key property of
WITH
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\&.
.PP
However, a
WITH
query can be marked
NOT MATERIALIZED
to remove this guarantee\&. In that case, the
WITH
query can be folded into the primary query much as though it were a simple sub\-SELECT
in the primary query\*(Aqs
FROM
clause\&. This results in duplicate computations if the primary query refers to that
WITH
query more than once; but if each such use requires only a few rows of the
WITH
query\*(Aqs total output,
NOT MATERIALIZED
can provide a net savings by allowing the queries to be optimized jointly\&.
NOT MATERIALIZED
is ignored if it is attached to a
WITH
query that is recursive or is not side\-effect\-free (i\&.e\&., is not a plain
SELECT
containing no volatile functions)\&.
.PP
By default, a side\-effect\-free
WITH
query is folded into the primary query if it is used exactly once in the primary query\*(Aqs
FROM
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
WITH
query as
MATERIALIZED\&. That might be useful, for example, if the
WITH
query is being used as an optimization fence to prevent the planner from choosing a bad plan\&.
PostgreSQL
versions before v12 never did such folding, so queries written for older versions might rely on
WITH
to act as an optimization fence\&.
.PP
See
Section\ \&7.8
for additional information\&.
.SS "FROM Clause"
.PP
The
FROM
clause specifies one or more source tables for the
\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
WHERE) to restrict the returned rows to a small subset of the Cartesian product\&.
.PP
The
FROM
clause can contain the following elements:
.PP
\fItable_name\fR
.RS 4
The name (optionally schema\-qualified) of an existing table or view\&. If
ONLY
is specified before the table name, only that table is scanned\&. If
ONLY
is not specified, the table and all its descendant tables (if any) are scanned\&. Optionally,
*
can be specified after the table name to explicitly indicate that descendant tables are included\&.
.RE
.PP
\fIalias\fR
.RS 4
A substitute name for the
FROM
item containing the alias\&. An alias is used for brevity or to eliminate ambiguity for self\-joins (where the same table is scanned multiple times)\&. When an alias is provided, it completely hides the actual name of the table or function; for example given
FROM foo AS f, the remainder of the
\fBSELECT\fR
must refer to this
FROM
item as
f
not
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\&.
.RE
.PP
TABLESAMPLE \fIsampling_method\fR ( \fIargument\fR [, \&.\&.\&.] ) [ REPEATABLE ( \fIseed\fR ) ]
.RS 4
A
TABLESAMPLE
clause after a
\fItable_name\fR
indicates that the specified
\fIsampling_method\fR
should be used to retrieve a subset of the rows in that table\&. This sampling precedes the application of any other filters such as
WHERE
clauses\&. The standard
PostgreSQL
distribution includes two sampling methods,
BERNOULLI
and
SYSTEM, and other sampling methods can be installed in the database via extensions\&.
.sp
The
BERNOULLI
and
SYSTEM
sampling methods each accept a single
\fIargument\fR
which is the fraction of the table to sample, expressed as a percentage between 0 and 100\&. This argument can be any
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
BERNOULLI
method scans the whole table and selects or ignores individual rows independently with the specified probability\&. The
SYSTEM
method does block\-level sampling with each block having the specified chance of being selected; all rows in each selected block are returned\&. The
SYSTEM
method is significantly faster than the
BERNOULLI
method when small sampling percentages are specified, but it may return a less\-random sample of the table as a result of clustering effects\&.
.sp
The optional
REPEATABLE
clause specifies a
\fIseed\fR
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
\fIargument\fR
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
REPEATABLE
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
REPEATABLE, and will always produce new samples on each use\&.
.RE
.PP
\fIselect\fR
.RS 4
A sub\-\fBSELECT\fR
can appear in the
FROM
clause\&. This acts as though its output were created as a temporary table for the duration of this single
\fBSELECT\fR
command\&. Note that the sub\-\fBSELECT\fR
must be surrounded by parentheses, and an alias
\fImust\fR
be provided for it\&. A
\fBVALUES\fR
command can also be used here\&.
.RE
.PP
\fIwith_query_name\fR
.RS 4
A
WITH
query is referenced by writing its name, just as though the query\*(Aqs name were a table name\&. (In fact, the
WITH
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\&.
.RE
.PP
\fIfunction_name\fR
.RS 4
Function calls can appear in the
FROM
clause\&. (This is especially useful for functions that return result sets, but any function can be used\&.) This acts as though the function\*(Aqs output were created as a temporary table for the duration of this single
\fBSELECT\fR
command\&. If the function\*(Aqs result type is composite (including the case of a function with multiple
OUT
parameters), each attribute becomes a separate column in the implicit table\&.
.sp
When the optional
\fBWITH ORDINALITY\fR
clause is added to the function call, an additional column of type
bigint
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
ordinality\&.
.sp
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\&.
.sp
Multiple function calls can be combined into a single
FROM\-clause item by surrounding them with
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\&.
.sp
If the function has been defined as returning the
record
data type, then an alias or the key word
AS
must be present, followed by a column definition list in the form
( \fIcolumn_name\fR \fIdata_type\fR [, \&.\&.\&. ])\&. The column definition list must match the actual number and types of columns returned by the function\&.
.sp
When using the
ROWS FROM( \&.\&.\&. )
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
ROWS FROM( \&.\&.\&. )\&. A column definition list can be placed after the
ROWS FROM( \&.\&.\&. )
construct only if there\*(Aqs just a single function and no
WITH ORDINALITY
clause\&.
.sp
To use
ORDINALITY
together with a column definition list, you must use the
ROWS FROM( \&.\&.\&. )
syntax and put the column definition list inside
ROWS FROM( \&.\&.\&. )\&.
.RE
.PP
\fIjoin_type\fR
.RS 4
One of
.sp
.RS 4
.ie n \{\
\h'-04'\(bu\h'+03'\c
.\}
.el \{\
.sp -1
.IP \(bu 2.3
.\}
[ INNER ] JOIN
.RE
.sp
.RS 4
.ie n \{\
\h'-04'\(bu\h'+03'\c
.\}
.el \{\
.sp -1
.IP \(bu 2.3
.\}
LEFT [ OUTER ] JOIN
.RE
.sp
.RS 4
.ie n \{\
\h'-04'\(bu\h'+03'\c
.\}
.el \{\
.sp -1
.IP \(bu 2.3
.\}
RIGHT [ OUTER ] JOIN
.RE
.sp
.RS 4
.ie n \{\
\h'-04'\(bu\h'+03'\c
.\}
.el \{\
.sp -1
.IP \(bu 2.3
.\}
FULL [ OUTER ] JOIN
.RE
.sp
For the
INNER
and
OUTER
join types, a join condition must be specified, namely exactly one of
ON \fIjoin_condition\fR,
USING (\fIjoin_column\fR [, \&.\&.\&.]), or
NATURAL\&. See below for the meaning\&.
.sp
A
JOIN
clause combines two
FROM
items, which for convenience we will refer to as
\(lqtables\(rq, though in reality they can be any type of
FROM
item\&. Use parentheses if necessary to determine the order of nesting\&. In the absence of parentheses,
JOINs nest left\-to\-right\&. In any case
JOIN
binds more tightly than the commas separating
FROM\-list items\&. All the
JOIN
options are just a notational convenience, since they do nothing you couldn\*(Aqt do with plain
FROM
and
WHERE\&.
.sp
LEFT OUTER JOIN
returns all rows in the qualified Cartesian product (i\&.e\&., all combined rows that pass its join condition), plus one copy of each row in the left\-hand table for which there was no right\-hand row that passed the join condition\&. This left\-hand row is extended to the full width of the joined table by inserting null values for the right\-hand columns\&. Note that only the
JOIN
clause\*(Aqs own condition is considered while deciding which rows have matches\&. Outer conditions are applied afterwards\&.
.sp
Conversely,
RIGHT OUTER JOIN
returns all the joined rows, plus one row for each unmatched right\-hand row (extended with nulls on the left)\&. This is just a notational convenience, since you could convert it to a
LEFT OUTER JOIN
by switching the left and right tables\&.
.sp
FULL OUTER JOIN
returns all the joined rows, plus one row for each unmatched left\-hand row (extended with nulls on the right), plus one row for each unmatched right\-hand row (extended with nulls on the left)\&.
.RE
.PP
ON \fIjoin_condition\fR
.RS 4
\fIjoin_condition\fR
is an expression resulting in a value of type
boolean
(similar to a
WHERE
clause) that specifies which rows in a join are considered to match\&.
.RE
.PP
USING ( \fIjoin_column\fR [, \&.\&.\&.] ) [ AS \fIjoin_using_alias\fR ]
.RS 4
A clause of the form
USING ( a, b, \&.\&.\&. )
is shorthand for
ON left_table\&.a = right_table\&.a AND left_table\&.b = right_table\&.b \&.\&.\&.\&. Also,
USING
implies that only one of each pair of equivalent columns will be included in the join output, not both\&.
.sp
If a
\fIjoin_using_alias\fR
name is specified, it provides a table alias for the join columns\&. Only the join columns listed in the
USING
clause are addressable by this name\&. Unlike a regular
\fIalias\fR, this does not hide the names of the joined tables from the rest of the query\&. Also unlike a regular
\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
USING
list\&.
.RE
.PP
NATURAL
.RS 4
NATURAL
is shorthand for a
USING
list that mentions all columns in the two tables that have matching names\&. If there are no common column names,
NATURAL
is equivalent to
ON TRUE\&.
.RE
.PP
CROSS JOIN
.RS 4
CROSS JOIN
is equivalent to
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
FROM, but restricted by the join condition (if any)\&.
.RE
.PP
LATERAL
.RS 4
The
LATERAL
key word can precede a sub\-\fBSELECT\fR
FROM
item\&. This allows the sub\-\fBSELECT\fR
to refer to columns of
FROM
items that appear before it in the
FROM
list\&. (Without
LATERAL, each sub\-\fBSELECT\fR
is evaluated independently and so cannot cross\-reference any other
FROM
item\&.)
.sp
LATERAL
can also precede a function\-call
FROM
item, but in this case it is a noise word, because the function expression can refer to earlier
FROM
items in any case\&.
.sp
A
LATERAL
item can appear at top level in the
FROM
list, or within a
JOIN
tree\&. In the latter case it can also refer to any items that are on the left\-hand side of a
JOIN
that it is on the right\-hand side of\&.
.sp
When a
FROM
item contains
LATERAL
cross\-references, evaluation proceeds as follows: for each row of the
FROM
item providing the cross\-referenced column(s), or set of rows of multiple
FROM
items providing the columns, the
LATERAL
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)\&.
.sp
The column source table(s) must be
INNER
or
LEFT
joined to the
LATERAL
item, else there would not be a well\-defined set of rows from which to compute each set of rows for the
LATERAL
item\&. Thus, although a construct such as
\fIX\fR RIGHT JOIN LATERAL \fIY\fR
is syntactically valid, it is not actually allowed for
\fIY\fR
to reference
\fIX\fR\&.
.RE
.SS "WHERE Clause"
.PP
The optional
WHERE
clause has the general form
.sp
.if n \{\
.RS 4
.\}
.nf
WHERE \fIcondition\fR
.fi
.if n \{\
.RE
.\}
.sp
where
\fIcondition\fR
is any expression that evaluates to a result of type
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\&.
.SS "GROUP BY Clause"
.PP
The optional
GROUP BY
clause has the general form
.sp
.if n \{\
.RS 4
.\}
.nf
GROUP BY [ ALL | DISTINCT ] \fIgrouping_element\fR [, \&.\&.\&.]
.fi
.if n \{\
.RE
.\}
.PP
GROUP BY
will condense into a single row all selected rows that share the same values for the grouped expressions\&. An
\fIexpression\fR
used inside a
\fIgrouping_element\fR
can be an input column name, or the name or ordinal number of an output column (\fBSELECT\fR
list item), or an arbitrary expression formed from input\-column values\&. In case of ambiguity, a
GROUP BY
name will be interpreted as an input\-column name rather than an output column name\&.
.PP
If any of
GROUPING SETS,
ROLLUP
or
CUBE
are present as grouping elements, then the
GROUP BY
clause as a whole defines some number of independent
\fIgrouping sets\fR\&. The effect of this is equivalent to constructing a
UNION ALL
between subqueries with the individual grouping sets as their
GROUP BY
clauses\&. The optional
DISTINCT
clause removes duplicate sets before processing; it does
\fInot\fR
transform the
UNION ALL
into a
UNION DISTINCT\&. For further details on the handling of grouping sets see
Section\ \&7.2.4\&.
.PP
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
GROUP BY
clause, the query is treated as having a single group comprising all the selected rows\&.) The set of rows fed to each aggregate function can be further filtered by attaching a
FILTER
clause to the aggregate function call; see
Section\ \&4.2.7
for more information\&. When a
FILTER
clause is present, only those rows matching it are included in the input to that aggregate function\&.
.PP
When
GROUP BY
is present, or any aggregate functions are present, it is not valid for the
\fBSELECT\fR
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\&.
.PP
Keep in mind that all aggregate functions are evaluated before evaluating any
\(lqscalar\(rq
expressions in the
HAVING
clause or
SELECT
list\&. This means that, for example, a
CASE
expression cannot be used to skip evaluation of an aggregate function; see
Section\ \&4.2.14\&.
.PP
Currently,
FOR NO KEY UPDATE,
FOR UPDATE,
FOR SHARE
and
FOR KEY SHARE
cannot be specified with
GROUP BY\&.
.SS "HAVING Clause"
.PP
The optional
HAVING
clause has the general form
.sp
.if n \{\
.RS 4
.\}
.nf
HAVING \fIcondition\fR
.fi
.if n \{\
.RE
.\}
.sp
where
\fIcondition\fR
is the same as specified for the
WHERE
clause\&.
.PP
HAVING
eliminates group rows that do not satisfy the condition\&.
HAVING
is different from
WHERE:
WHERE
filters individual rows before the application of
GROUP BY, while
HAVING
filters group rows created by
GROUP BY\&. Each column referenced in
\fIcondition\fR
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\&.
.PP
The presence of
HAVING
turns a query into a grouped query even if there is no
GROUP BY
clause\&. This is the same as what happens when the query contains aggregate functions but no
GROUP BY
clause\&. All the selected rows are considered to form a single group, and the
\fBSELECT\fR
list and
HAVING
clause can only reference table columns from within aggregate functions\&. Such a query will emit a single row if the
HAVING
condition is true, zero rows if it is not true\&.
.PP
Currently,
FOR NO KEY UPDATE,
FOR UPDATE,
FOR SHARE
and
FOR KEY SHARE
cannot be specified with
HAVING\&.
.SS "WINDOW Clause"
.PP
The optional
WINDOW
clause has the general form
.sp
.if n \{\
.RS 4
.\}
.nf
WINDOW \fIwindow_name\fR AS ( \fIwindow_definition\fR ) [, \&.\&.\&.]
.fi
.if n \{\
.RE
.\}
.sp
where
\fIwindow_name\fR
is a name that can be referenced from
OVER
clauses or subsequent window definitions, and
\fIwindow_definition\fR
is
.sp
.if n \{\
.RS 4
.\}
.nf
[ \fIexisting_window_name\fR ]
[ PARTITION BY \fIexpression\fR [, \&.\&.\&.] ]
[ ORDER BY \fIexpression\fR [ ASC | DESC | USING \fIoperator\fR ] [ NULLS { FIRST | LAST } ] [, \&.\&.\&.] ]
[ \fIframe_clause\fR ]
.fi
.if n \{\
.RE
.\}
.PP
If an
\fIexisting_window_name\fR
is specified it must refer to an earlier entry in the
WINDOW
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
PARTITION BY
clause, and it can specify
ORDER BY
only if the copied window does not have one\&. The new window always uses its own frame clause; the copied window must not specify a frame clause\&.
.PP
The elements of the
PARTITION BY
list are interpreted in much the same fashion as elements of a
GROUP BY
clause, except that they are always simple expressions and never the name or number of an output column\&. Another difference is that these expressions can contain aggregate function calls, which are not allowed in a regular
GROUP BY
clause\&. They are allowed here because windowing occurs after grouping and aggregation\&.
.PP
Similarly, the elements of the
ORDER BY
list are interpreted in much the same fashion as elements of a statement\-level
ORDER BY
clause, except that the expressions are always taken as simple expressions and never the name or number of an output column\&.
.PP
The optional
\fIframe_clause\fR
defines the
window frame
for window functions that depend on the frame (not all do)\&. The window frame is a set of related rows for each row of the query (called the
current row)\&. The
\fIframe_clause\fR
can be one of
.sp
.if n \{\
.RS 4
.\}
.nf
{ RANGE | ROWS | GROUPS } \fIframe_start\fR [ \fIframe_exclusion\fR ]
{ RANGE | ROWS | GROUPS } BETWEEN \fIframe_start\fR AND \fIframe_end\fR [ \fIframe_exclusion\fR ]
.fi
.if n \{\
.RE
.\}
.sp
where
\fIframe_start\fR
and
\fIframe_end\fR
can be one of
.sp
.if n \{\
.RS 4
.\}
.nf
UNBOUNDED PRECEDING
\fIoffset\fR PRECEDING
CURRENT ROW
\fIoffset\fR FOLLOWING
UNBOUNDED FOLLOWING
.fi
.if n \{\
.RE
.\}
.sp
and
\fIframe_exclusion\fR
can be one of
.sp
.if n \{\
.RS 4
.\}
.nf
EXCLUDE CURRENT ROW
EXCLUDE GROUP
EXCLUDE TIES
EXCLUDE NO OTHERS
.fi
.if n \{\
.RE
.\}
.sp
If
\fIframe_end\fR
is omitted it defaults to
CURRENT ROW\&. Restrictions are that
\fIframe_start\fR
cannot be
UNBOUNDED FOLLOWING,
\fIframe_end\fR
cannot be
UNBOUNDED PRECEDING, and the
\fIframe_end\fR
choice cannot appear earlier in the above list of
\fIframe_start\fR
and
\fIframe_end\fR
options than the
\fIframe_start\fR
choice does \(em for example
RANGE BETWEEN CURRENT ROW AND \fIoffset\fR PRECEDING
is not allowed\&.
.PP
The default framing option is
RANGE UNBOUNDED PRECEDING, which is the same as
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
peer
(a row that the window\*(Aqs
ORDER BY
clause considers equivalent to the current row; all rows are peers if there is no
ORDER BY)\&. In general,
UNBOUNDED PRECEDING
means that the frame starts with the first row of the partition, and similarly
UNBOUNDED FOLLOWING
means that the frame ends with the last row of the partition, regardless of
RANGE,
ROWS
or
GROUPS
mode\&. In
ROWS
mode,
CURRENT ROW
means that the frame starts or ends with the current row; but in
RANGE
or
GROUPS
mode it means that the frame starts or ends with the current row\*(Aqs first or last peer in the
ORDER BY
ordering\&. The
\fIoffset\fR
PRECEDING
and
\fIoffset\fR
FOLLOWING
options vary in meaning depending on the frame mode\&. In
ROWS
mode, the
\fIoffset\fR
is an integer indicating that the frame starts or ends that many rows before or after the current row\&. In
GROUPS
mode, the
\fIoffset\fR
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
peer group
is a group of rows that are equivalent according to the window\*(Aqs
ORDER BY
clause\&. In
RANGE
mode, use of an
\fIoffset\fR
option requires that there be exactly one
ORDER BY
column in the window definition\&. Then the frame contains those rows whose ordering column value is no more than
\fIoffset\fR
less than (for
PRECEDING) or more than (for
FOLLOWING) the current row\*(Aqs ordering column value\&. In these cases the data type of the
\fIoffset\fR
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
interval\&. In all these cases, the value of the
\fIoffset\fR
must be non\-null and non\-negative\&. Also, while the
\fIoffset\fR
does not have to be a simple constant, it cannot contain variables, aggregate functions, or window functions\&.
.PP
The
\fIframe_exclusion\fR
option allows rows around the current row to be excluded from the frame, even if they would be included according to the frame start and frame end options\&.
EXCLUDE CURRENT ROW
excludes the current row from the frame\&.
EXCLUDE GROUP
excludes the current row and its ordering peers from the frame\&.
EXCLUDE TIES
excludes any peers of the current row from the frame, but not the current row itself\&.
EXCLUDE NO OTHERS
simply specifies explicitly the default behavior of not excluding the current row or its peers\&.
.PP
Beware that the
ROWS
mode can produce unpredictable results if the
ORDER BY
ordering does not order the rows uniquely\&. The
RANGE
and
GROUPS
modes are designed to ensure that rows that are peers in the
ORDER BY
ordering are treated alike: all rows of a given peer group will be in the frame or excluded from it\&.
.PP
The purpose of a
WINDOW
clause is to specify the behavior of
window functions
appearing in the query\*(Aqs
\fBSELECT\fR list
or
ORDER BY
clause\&. These functions can reference the
WINDOW
clause entries by name in their
OVER
clauses\&. A
WINDOW
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
WINDOW
clause at all, since a window function call can specify its window definition directly in its
OVER
clause\&. However, the
WINDOW
clause saves typing when the same window definition is needed for more than one window function\&.
.PP
Currently,
FOR NO KEY UPDATE,
FOR UPDATE,
FOR SHARE
and
FOR KEY SHARE
cannot be specified with
WINDOW\&.
.PP
Window functions are described in detail in
Section\ \&3.5,
Section\ \&4.2.8, and
Section\ \&7.2.5\&.
.SS "SELECT List"
.PP
The
\fBSELECT\fR
list (between the key words
SELECT
and
FROM) specifies expressions that form the output rows of the
\fBSELECT\fR
statement\&. The expressions can (and usually do) refer to columns computed in the
FROM
clause\&.
.PP
Just as in a table, every output column of a
\fBSELECT\fR
has a name\&. In a simple
\fBSELECT\fR
this name is just used to label the column for display, but when the
\fBSELECT\fR
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
AS
\fIoutput_name\fR
after the column\*(Aqs expression\&. (You can omit
AS, but only if the desired output name does not match any
PostgreSQL
keyword (see
Appendix\ \&C)\&. For protection against possible future keyword additions, it is recommended that you always either write
AS
or double\-quote the output name\&.) If you do not specify a column name, a name is chosen automatically by
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
?column?\&.
.PP
An output column\*(Aqs name can be used to refer to the column\*(Aqs value in
ORDER BY
and
GROUP BY
clauses, but not in the
WHERE
or
HAVING
clauses; there you must write out the expression instead\&.
.PP
Instead of an expression,
*
can be written in the output list as a shorthand for all the columns of the selected rows\&. Also, you can write
\fItable_name\fR\&.*
as a shorthand for the columns coming from just that table\&. In these cases it is not possible to specify new names with
AS; the output column names will be the same as the table columns\*(Aq names\&.
.PP
According to the SQL standard, the expressions in the output list should be computed before applying
DISTINCT,
ORDER BY, or
LIMIT\&. This is obviously necessary when using
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
ORDER BY
and
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\&.
PostgreSQL
will effectively evaluate output expressions after sorting and limiting, so long as those expressions are not referenced in
DISTINCT,
ORDER BY
or
GROUP BY\&. (As a counterexample,
SELECT f(x) FROM tab ORDER BY 1
clearly must evaluate
\fBf(x)\fR
before sorting\&.) Output expressions that contain set\-returning functions are effectively evaluated after sorting and before limiting, so that
LIMIT
will act to cut off the output from a set\-returning function\&.
.if n \{\
.sp
.\}
.RS 4
.it 1 an-trap
.nr an-no-space-flag 1
.nr an-break-flag 1
.br
.ps +1
\fBNote\fR
.ps -1
.br
.PP
PostgreSQL
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\&.
.sp .5v
.RE
.SS "DISTINCT Clause"
.PP
If
SELECT DISTINCT
is specified, all duplicate rows are removed from the result set (one row is kept from each group of duplicates)\&.
SELECT ALL
specifies the opposite: all rows are kept; that is the default\&.
.PP
SELECT DISTINCT ON ( \fIexpression\fR [, \&.\&.\&.] )
keeps only the first row of each set of rows where the given expressions evaluate to equal\&. The
DISTINCT ON
expressions are interpreted using the same rules as for
ORDER BY
(see above)\&. Note that the
\(lqfirst row\(rq
of each set is unpredictable unless
ORDER BY
is used to ensure that the desired row appears first\&. For example:
.sp
.if n \{\
.RS 4
.\}
.nf
SELECT DISTINCT ON (location) location, time, report
    FROM weather_reports
    ORDER BY location, time DESC;
.fi
.if n \{\
.RE
.\}
.sp
retrieves the most recent weather report for each location\&. But if we had not used
ORDER BY
to force descending order of time values for each location, we\*(Aqd have gotten a report from an unpredictable time for each location\&.
.PP
The
DISTINCT ON
expression(s) must match the leftmost
ORDER BY
expression(s)\&. The
ORDER BY
clause will normally contain additional expression(s) that determine the desired precedence of rows within each
DISTINCT ON
group\&.
.PP
Currently,
FOR NO KEY UPDATE,
FOR UPDATE,
FOR SHARE
and
FOR KEY SHARE
cannot be specified with
DISTINCT\&.
.SS "UNION Clause"
.PP
The
UNION
clause has this general form:
.sp
.if n \{\
.RS 4
.\}
.nf
\fIselect_statement\fR UNION [ ALL | DISTINCT ] \fIselect_statement\fR
.fi
.if n \{\
.RE
.\}
.sp
\fIselect_statement\fR
is any
\fBSELECT\fR
statement without an
ORDER BY,
LIMIT,
FOR NO KEY UPDATE,
FOR UPDATE,
FOR SHARE, or
FOR KEY SHARE
clause\&. (ORDER BY
and
LIMIT
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
UNION, not to its right\-hand input expression\&.)
.PP
The
UNION
operator computes the set union of the rows returned by the involved
\fBSELECT\fR
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
\fBSELECT\fR
statements that represent the direct operands of the
UNION
must produce the same number of columns, and corresponding columns must be of compatible data types\&.
.PP
The result of
UNION
does not contain any duplicate rows unless the
ALL
option is specified\&.
ALL
prevents elimination of duplicates\&. (Therefore,
UNION ALL
is usually significantly quicker than
UNION; use
ALL
when you can\&.)
DISTINCT
can be written to explicitly specify the default behavior of eliminating duplicate rows\&.
.PP
Multiple
UNION
operators in the same
\fBSELECT\fR
statement are evaluated left to right, unless otherwise indicated by parentheses\&.
.PP
Currently,
FOR NO KEY UPDATE,
FOR UPDATE,
FOR SHARE
and
FOR KEY SHARE
cannot be specified either for a
UNION
result or for any input of a
UNION\&.
.SS "INTERSECT Clause"
.PP
The
INTERSECT
clause has this general form:
.sp
.if n \{\
.RS 4
.\}
.nf
\fIselect_statement\fR INTERSECT [ ALL | DISTINCT ] \fIselect_statement\fR
.fi
.if n \{\
.RE
.\}
.sp
\fIselect_statement\fR
is any
\fBSELECT\fR
statement without an
ORDER BY,
LIMIT,
FOR NO KEY UPDATE,
FOR UPDATE,
FOR SHARE, or
FOR KEY SHARE
clause\&.
.PP
The
INTERSECT
operator computes the set intersection of the rows returned by the involved
\fBSELECT\fR
statements\&. A row is in the intersection of two result sets if it appears in both result sets\&.
.PP
The result of
INTERSECT
does not contain any duplicate rows unless the
ALL
option is specified\&. With
ALL, a row that has
\fIm\fR
duplicates in the left table and
\fIn\fR
duplicates in the right table will appear min(\fIm\fR,\fIn\fR) times in the result set\&.
DISTINCT
can be written to explicitly specify the default behavior of eliminating duplicate rows\&.
.PP
Multiple
INTERSECT
operators in the same
\fBSELECT\fR
statement are evaluated left to right, unless parentheses dictate otherwise\&.
INTERSECT
binds more tightly than
UNION\&. That is,
A UNION B INTERSECT C
will be read as
A UNION (B INTERSECT C)\&.
.PP
Currently,
FOR NO KEY UPDATE,
FOR UPDATE,
FOR SHARE
and
FOR KEY SHARE
cannot be specified either for an
INTERSECT
result or for any input of an
INTERSECT\&.
.SS "EXCEPT Clause"
.PP
The
EXCEPT
clause has this general form:
.sp
.if n \{\
.RS 4
.\}
.nf
\fIselect_statement\fR EXCEPT [ ALL | DISTINCT ] \fIselect_statement\fR
.fi
.if n \{\
.RE
.\}
.sp
\fIselect_statement\fR
is any
\fBSELECT\fR
statement without an
ORDER BY,
LIMIT,
FOR NO KEY UPDATE,
FOR UPDATE,
FOR SHARE, or
FOR KEY SHARE
clause\&.
.PP
The
EXCEPT
operator computes the set of rows that are in the result of the left
\fBSELECT\fR
statement but not in the result of the right one\&.
.PP
The result of
EXCEPT
does not contain any duplicate rows unless the
ALL
option is specified\&. With
ALL, a row that has
\fIm\fR
duplicates in the left table and
\fIn\fR
duplicates in the right table will appear max(\fIm\fR\-\fIn\fR,0) times in the result set\&.
DISTINCT
can be written to explicitly specify the default behavior of eliminating duplicate rows\&.
.PP
Multiple
EXCEPT
operators in the same
\fBSELECT\fR
statement are evaluated left to right, unless parentheses dictate otherwise\&.
EXCEPT
binds at the same level as
UNION\&.
.PP
Currently,
FOR NO KEY UPDATE,
FOR UPDATE,
FOR SHARE
and
FOR KEY SHARE
cannot be specified either for an
EXCEPT
result or for any input of an
EXCEPT\&.
.SS "ORDER BY Clause"
.PP
The optional
ORDER BY
clause has this general form:
.sp
.if n \{\
.RS 4
.\}
.nf
ORDER BY \fIexpression\fR [ ASC | DESC | USING \fIoperator\fR ] [ NULLS { FIRST | LAST } ] [, \&.\&.\&.]
.fi
.if n \{\
.RE
.\}
.sp
The
ORDER BY
clause causes the result rows to be sorted according to the specified expression(s)\&. If two rows are equal according to the leftmost expression, they are compared according to the next expression and so on\&. If they are equal according to all specified expressions, they are returned in an implementation\-dependent order\&.
.PP
Each
\fIexpression\fR
can be the name or ordinal number of an output column (\fBSELECT\fR
list item), or it can be an arbitrary expression formed from input\-column values\&.
.PP
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
AS
clause\&.
.PP
It is also possible to use arbitrary expressions in the
ORDER BY
clause, including columns that do not appear in the
\fBSELECT\fR
output list\&. Thus the following statement is valid:
.sp
.if n \{\
.RS 4
.\}
.nf
SELECT name FROM distributors ORDER BY code;
.fi
.if n \{\
.RE
.\}
.sp
A limitation of this feature is that an
ORDER BY
clause applying to the result of a
UNION,
INTERSECT, or
EXCEPT
clause can only specify an output column name or number, not an expression\&.
.PP
If an
ORDER BY
expression is a simple name that matches both an output column name and an input column name,
ORDER BY
will interpret it as the output column name\&. This is the opposite of the choice that
GROUP BY
will make in the same situation\&. This inconsistency is made to be compatible with the SQL standard\&.
.PP
Optionally one can add the key word
ASC
(ascending) or
DESC
(descending) after any expression in the
ORDER BY
clause\&. If not specified,
ASC
is assumed by default\&. Alternatively, a specific ordering operator name can be specified in the
USING
clause\&. An ordering operator must be a less\-than or greater\-than member of some B\-tree operator family\&.
ASC
is usually equivalent to
USING <
and
DESC
is usually equivalent to
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\&.)
.PP
If
NULLS LAST
is specified, null values sort after all non\-null values; if
NULLS FIRST
is specified, null values sort before all non\-null values\&. If neither is specified, the default behavior is
NULLS LAST
when
ASC
is specified or implied, and
NULLS FIRST
when
DESC
is specified (thus, the default is to act as though nulls are larger than non\-nulls)\&. When
USING
is specified, the default nulls ordering depends on whether the operator is a less\-than or greater\-than operator\&.
.PP
Note that ordering options apply only to the expression they follow; for example
ORDER BY x, y DESC
does not mean the same thing as
ORDER BY x DESC, y DESC\&.
.PP
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
COLLATE
clause in the
\fIexpression\fR, for example
ORDER BY mycolumn COLLATE "en_US"\&. For more information see
Section\ \&4.2.10
and
Section\ \&24.2\&.
.SS "LIMIT Clause"
.PP
The
LIMIT
clause consists of two independent sub\-clauses:
.sp
.if n \{\
.RS 4
.\}
.nf
LIMIT { \fIcount\fR | ALL }
OFFSET \fIstart\fR
.fi
.if n \{\
.RE
.\}
.sp
The parameter
\fIcount\fR
specifies the maximum number of rows to return, while
\fIstart\fR
specifies the number of rows to skip before starting to return rows\&. When both are specified,
\fIstart\fR
rows are skipped before starting to count the
\fIcount\fR
rows to be returned\&.
.PP
If the
\fIcount\fR
expression evaluates to NULL, it is treated as
LIMIT ALL, i\&.e\&., no limit\&. If
\fIstart\fR
evaluates to NULL, it is treated the same as
OFFSET 0\&.
.PP
SQL:2008 introduced a different syntax to achieve the same result, which
PostgreSQL
also supports\&. It is:
.sp
.if n \{\
.RS 4
.\}
.nf
OFFSET \fIstart\fR { ROW | ROWS }
FETCH { FIRST | NEXT } [ \fIcount\fR ] { ROW | ROWS } { ONLY | WITH TIES }
.fi
.if n \{\
.RE
.\}
.sp
In this syntax, the
\fIstart\fR
or
\fIcount\fR
value is required by the standard to be a literal constant, a parameter, or a variable name; as a
PostgreSQL
extension, other expressions are allowed, but will generally need to be enclosed in parentheses to avoid ambiguity\&. If
\fIcount\fR
is omitted in a
FETCH
clause, it defaults to 1\&. The
WITH TIES
option is used to return any additional rows that tie for the last place in the result set according to the
ORDER BY
clause;
ORDER BY
is mandatory in this case, and
SKIP LOCKED
is not allowed\&.
ROW
and
ROWS
as well as
FIRST
and
NEXT
are noise words that don\*(Aqt influence the effects of these clauses\&. According to the standard, the
OFFSET
clause must come before the
FETCH
clause if both are present; but
PostgreSQL
is laxer and allows either order\&.
.PP
When using
LIMIT, it is a good idea to use an
ORDER BY
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
ORDER BY\&.
.PP
The query planner takes
LIMIT
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
LIMIT
and
OFFSET\&. Thus, using different
LIMIT/OFFSET
values to select different subsets of a query result
\fIwill give inconsistent results\fR
unless you enforce a predictable result ordering with
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
ORDER BY
is used to constrain the order\&.
.PP
It is even possible for repeated executions of the same
LIMIT
query to return different subsets of the rows of a table, if there is not an
ORDER BY
to enforce selection of a deterministic subset\&. Again, this is not a bug; determinism of the results is simply not guaranteed in such a case\&.
.SS "The Locking Clause"
.PP
FOR UPDATE,
FOR NO KEY UPDATE,
FOR SHARE
and
FOR KEY SHARE
are
locking clauses; they affect how
SELECT
locks rows as they are obtained from the table\&.
.PP
The locking clause has the general form
.sp
.if n \{\
.RS 4
.\}
.nf
FOR \fIlock_strength\fR [ OF \fItable_name\fR [, \&.\&.\&.] ] [ NOWAIT | SKIP LOCKED ]
.fi
.if n \{\
.RE
.\}
.sp
where
\fIlock_strength\fR
can be one of
.sp
.if n \{\
.RS 4
.\}
.nf
UPDATE
NO KEY UPDATE
SHARE
KEY SHARE
.fi
.if n \{\
.RE
.\}
.PP
For more information on each row\-level lock mode, refer to
Section\ \&13.3.2\&.
.PP
To prevent the operation from waiting for other transactions to commit, use either the
NOWAIT
or
SKIP LOCKED
option\&. With
NOWAIT, the statement reports an error, rather than waiting, if a selected row cannot be locked immediately\&. With
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
NOWAIT
and
SKIP LOCKED
apply only to the row\-level lock(s) \(em the required
ROW SHARE
table\-level lock is still taken in the ordinary way (see
Chapter\ \&13)\&. You can use
\fBLOCK\fR
with the
NOWAIT
option first, if you need to acquire the table\-level lock without waiting\&.
.PP
If specific tables are named in a locking clause, then only rows coming from those tables are locked; any other tables used in the
\fBSELECT\fR
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
WITH
queries referenced by the primary query\&. If you want row locking to occur within a
WITH
query, specify a locking clause within the
WITH
query\&.
.PP
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
NOWAIT
if that is specified in any of the clauses affecting it\&. Otherwise, it is processed as
SKIP LOCKED
if that is specified in any of the clauses affecting it\&.
.PP
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\&.
.PP
When a locking clause appears at the top level of a
\fBSELECT\fR
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
LIMIT
is used, locking stops once enough rows have been returned to satisfy the limit (but note that rows skipped over by
OFFSET
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\&.
.PP
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,
.sp
.if n \{\
.RS 4
.\}
.nf
SELECT * FROM (SELECT * FROM mytable FOR UPDATE) ss WHERE col1 = 5;
.fi
.if n \{\
.RE
.\}
.sp
will lock only rows having
col1 = 5, even though that condition is not textually within the sub\-query\&.
.PP
Previous releases failed to preserve a lock which is upgraded by a later savepoint\&. For example, this code:
.sp
.if n \{\
.RS 4
.\}
.nf
BEGIN;
SELECT * FROM mytable WHERE key = 1 FOR UPDATE;
SAVEPOINT s;
UPDATE mytable SET \&.\&.\&. WHERE key = 1;
ROLLBACK TO s;
.fi
.if n \{\
.RE
.\}
.sp
would fail to preserve the
FOR UPDATE
lock after the
\fBROLLBACK TO\fR\&. This has been fixed in release 9\&.3\&.
.if n \{\
.sp
.\}
.RS 4
.it 1 an-trap
.nr an-no-space-flag 1
.nr an-break-flag 1
.br
.ps +1
\fBCaution\fR
.ps -1
.br
.PP
It is possible for a
\fBSELECT\fR
command running at the
READ COMMITTED
transaction isolation level and using
ORDER BY
and a locking clause to return rows out of order\&. This is because
ORDER BY
is applied first\&. The command sorts the result, but might then block trying to obtain a lock on one or more of the rows\&. Once the
SELECT
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
FOR UPDATE/SHARE
clause in a sub\-query, for example
.sp
.if n \{\
.RS 4
.\}
.nf
SELECT * FROM (SELECT * FROM mytable FOR UPDATE) ss ORDER BY column1;
.fi
.if n \{\
.RE
.\}
.sp
Note that this will result in locking all rows of
mytable, whereas
FOR UPDATE
at the top level would lock only the actually returned rows\&. This can make for a significant performance difference, particularly if the
ORDER BY
is combined with
LIMIT
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\&.
.PP
At the
REPEATABLE READ
or
SERIALIZABLE
transaction isolation level this would cause a serialization failure (with an
SQLSTATE
of
\*(Aq40001\*(Aq), so there is no possibility of receiving rows out of order under these isolation levels\&.
.sp .5v
.RE
.SS "TABLE Command"
.PP
The command
.sp
.if n \{\
.RS 4
.\}
.nf
TABLE \fIname\fR
.fi
.if n \{\
.RE
.\}
.sp
is equivalent to
.sp
.if n \{\
.RS 4
.\}
.nf
SELECT * FROM \fIname\fR
.fi
.if n \{\
.RE
.\}
.sp
It can be used as a top\-level command or as a space\-saving syntax variant in parts of complex queries\&. Only the
WITH,
UNION,
INTERSECT,
EXCEPT,
ORDER BY,
LIMIT,
OFFSET,
FETCH
and
FOR
locking clauses can be used with
\fBTABLE\fR; the
WHERE
clause and any form of aggregation cannot be used\&.
.SH "EXAMPLES"
.PP
To join the table
films
with the table
distributors:
.sp
.if n \{\
.RS 4
.\}
.nf
SELECT f\&.title, f\&.did, d\&.name, f\&.date_prod, f\&.kind
    FROM distributors d JOIN films f USING (did);

       title       | did |     name     | date_prod  |   kind
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-
 The Third Man     | 101 | British Lion | 1949\-12\-23 | Drama
 The African Queen | 101 | British Lion | 1951\-08\-11 | Romantic
 \&.\&.\&.
.fi
.if n \{\
.RE
.\}
.PP
To sum the column
len
of all films and group the results by
kind:
.sp
.if n \{\
.RS 4
.\}
.nf
SELECT kind, sum(len) AS total FROM films GROUP BY kind;

   kind   | total
\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-
 Action   | 07:34
 Comedy   | 02:58
 Drama    | 14:28
 Musical  | 06:42
 Romantic | 04:38
.fi
.if n \{\
.RE
.\}
.PP
To sum the column
len
of all films, group the results by
kind
and show those group totals that are less than 5 hours:
.sp
.if n \{\
.RS 4
.\}
.nf
SELECT kind, sum(len) AS total
    FROM films
    GROUP BY kind
    HAVING sum(len) < interval \*(Aq5 hours\*(Aq;

   kind   | total
\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-
 Comedy   | 02:58
 Romantic | 04:38
.fi
.if n \{\
.RE
.\}
.PP
The following two examples are identical ways of sorting the individual results according to the contents of the second column (name):
.sp
.if n \{\
.RS 4
.\}
.nf
SELECT * FROM distributors ORDER BY name;
SELECT * FROM distributors ORDER BY 2;

 did |       name
\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
 109 | 20th Century Fox
 110 | Bavaria Atelier
 101 | British Lion
 107 | Columbia
 102 | Jean Luc Godard
 113 | Luso films
 104 | Mosfilm
 103 | Paramount
 106 | Toho
 105 | United Artists
 111 | Walt Disney
 112 | Warner Bros\&.
 108 | Westward
.fi
.if n \{\
.RE
.\}
.PP
The next example shows how to obtain the union of the tables
distributors
and
actors, restricting the results to those that begin with the letter W in each table\&. Only distinct rows are wanted, so the key word
ALL
is omitted\&.
.sp
.if n \{\
.RS 4
.\}
.nf
distributors:               actors:
 did |     name              id |     name
\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-        \-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
 108 | Westward               1 | Woody Allen
 111 | Walt Disney            2 | Warren Beatty
 112 | Warner Bros\&.           3 | Walter Matthau
 \&.\&.\&.                         \&.\&.\&.

SELECT distributors\&.name
    FROM distributors
    WHERE distributors\&.name LIKE \*(AqW%\*(Aq
UNION
SELECT actors\&.name
    FROM actors
    WHERE actors\&.name LIKE \*(AqW%\*(Aq;

      name
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
 Walt Disney
 Walter Matthau
 Warner Bros\&.
 Warren Beatty
 Westward
 Woody Allen
.fi
.if n \{\
.RE
.\}
.PP
This example shows how to use a function in the
FROM
clause, both with and without a column definition list:
.sp
.if n \{\
.RS 4
.\}
.nf
CREATE FUNCTION distributors(int) RETURNS SETOF distributors AS $$
    SELECT * FROM distributors WHERE did = $1;
$$ LANGUAGE SQL;

SELECT * FROM distributors(111);
 did |    name
\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-
 111 | Walt Disney

CREATE FUNCTION distributors_2(int) RETURNS SETOF record AS $$
    SELECT * FROM distributors WHERE did = $1;
$$ LANGUAGE SQL;

SELECT * FROM distributors_2(111) AS (f1 int, f2 text);
 f1  |     f2
\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-
 111 | Walt Disney
.fi
.if n \{\
.RE
.\}
.PP
Here is an example of a function with an ordinality column added:
.sp
.if n \{\
.RS 4
.\}
.nf
SELECT * FROM unnest(ARRAY[\*(Aqa\*(Aq,\*(Aqb\*(Aq,\*(Aqc\*(Aq,\*(Aqd\*(Aq,\*(Aqe\*(Aq,\*(Aqf\*(Aq]) WITH ORDINALITY;
 unnest | ordinality
\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-
 a      |        1
 b      |        2
 c      |        3
 d      |        4
 e      |        5
 f      |        6
(6 rows)
.fi
.if n \{\
.RE
.\}
.PP
This example shows how to use a simple
WITH
clause:
.sp
.if n \{\
.RS 4
.\}
.nf
WITH t AS (
    SELECT random() as x FROM generate_series(1, 3)
  )
SELECT * FROM t
UNION ALL
SELECT * FROM t;
         x
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
  0\&.534150459803641
  0\&.520092216785997
 0\&.0735620250925422
  0\&.534150459803641
  0\&.520092216785997
 0\&.0735620250925422
.fi
.if n \{\
.RE
.\}
.sp
Notice that the
WITH
query was evaluated only once, so that we got two sets of the same three random values\&.
.PP
This example uses
WITH RECURSIVE
to find all subordinates (direct or indirect) of the employee Mary, and their level of indirectness, from a table that shows only direct subordinates:
.sp
.if n \{\
.RS 4
.\}
.nf
WITH RECURSIVE employee_recursive(distance, employee_name, manager_name) AS (
    SELECT 1, employee_name, manager_name
    FROM employee
    WHERE manager_name = \*(AqMary\*(Aq
  UNION ALL
    SELECT er\&.distance + 1, e\&.employee_name, e\&.manager_name
    FROM employee_recursive er, employee e
    WHERE er\&.employee_name = e\&.manager_name
  )
SELECT distance, employee_name FROM employee_recursive;
.fi
.if n \{\
.RE
.\}
.sp
Notice the typical form of recursive queries: an initial condition, followed by
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
Section\ \&7.8
for more examples\&.)
.PP
This example uses
LATERAL
to apply a set\-returning function
\fBget_product_names()\fR
for each row of the
manufacturers
table:
.sp
.if n \{\
.RS 4
.\}
.nf
SELECT m\&.name AS mname, pname
FROM manufacturers m, LATERAL get_product_names(m\&.id) pname;
.fi
.if n \{\
.RE
.\}
.sp
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:
.sp
.if n \{\
.RS 4
.\}
.nf
SELECT m\&.name AS mname, pname
FROM manufacturers m LEFT JOIN LATERAL get_product_names(m\&.id) pname ON true;
.fi
.if n \{\
.RE
.\}
.SH "COMPATIBILITY"
.PP
Of course, the
\fBSELECT\fR
statement is compatible with the SQL standard\&. But there are some extensions and some missing features\&.
.SS "Omitted FROM Clauses"
.PP
PostgreSQL
allows one to omit the
FROM
clause\&. It has a straightforward use to compute the results of simple expressions:
.sp
.if n \{\
.RS 4
.\}
.nf
SELECT 2+2;

 ?column?
\-\-\-\-\-\-\-\-\-\-
        4
.fi
.if n \{\
.RE
.\}
.sp
Some other
SQL
databases cannot do this except by introducing a dummy one\-row table from which to do the
\fBSELECT\fR\&.
.SS "Empty SELECT Lists"
.PP
The list of output expressions after
SELECT
can be empty, producing a zero\-column result table\&. This is not valid syntax according to the SQL standard\&.
PostgreSQL
allows it to be consistent with allowing zero\-column tables\&. However, an empty list is not allowed when
DISTINCT
is used\&.
.SS "Omitting the AS Key Word"
.PP
In the SQL standard, the optional key word
AS
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)\&.
PostgreSQL
is slightly more restrictive:
AS
is required if the new column name matches any keyword at all, reserved or not\&. Recommended practice is to use
AS
or double\-quote output column names, to prevent any possible conflict against future keyword additions\&.
.PP
In
FROM
items, both the standard and
PostgreSQL
allow
AS
to be omitted before an alias that is an unreserved keyword\&. But this is impractical for output column names, because of syntactic ambiguities\&.
.SS "ONLY and Inheritance"
.PP
The SQL standard requires parentheses around the table name when writing
ONLY, for example
SELECT * FROM ONLY (tab1), ONLY (tab2) WHERE \&.\&.\&.\&.
PostgreSQL
considers these parentheses to be optional\&.
.PP
PostgreSQL
allows a trailing
*
to be written to explicitly specify the non\-ONLY
behavior of including child tables\&. The standard does not allow this\&.
.PP
(These points apply equally to all SQL commands supporting the
ONLY
option\&.)
.SS "TABLESAMPLE Clause Restrictions"
.PP
The
TABLESAMPLE
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
FROM
item\&.
.SS "Function Calls in FROM"
.PP
PostgreSQL
allows a function call to be written directly as a member of the
FROM
list\&. In the SQL standard it would be necessary to wrap such a function call in a sub\-\fBSELECT\fR; that is, the syntax
FROM \fIfunc\fR(\&.\&.\&.) \fIalias\fR
is approximately equivalent to
FROM LATERAL (SELECT \fIfunc\fR(\&.\&.\&.)) \fIalias\fR\&. Note that
LATERAL
is considered to be implicit; this is because the standard requires
LATERAL
semantics for an
UNNEST()
item in
FROM\&.
PostgreSQL
treats
UNNEST()
the same as other set\-returning functions\&.
.SS "Namespace Available to GROUP BY and ORDER BY"
.PP
In the SQL\-92 standard, an
ORDER BY
clause can only use output column names or numbers, while a
GROUP BY
clause can only use expressions based on input column names\&.
PostgreSQL
extends each of these clauses to allow the other choice as well (but it uses the standard\*(Aqs interpretation if there is ambiguity)\&.
PostgreSQL
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\&.
.PP
SQL:1999 and later use a slightly different definition which is not entirely upward compatible with SQL\-92\&. In most cases, however,
PostgreSQL
will interpret an
ORDER BY
or
GROUP BY
expression the same way SQL:1999 does\&.
.SS "Functional Dependencies"
.PP
PostgreSQL
recognizes functional dependency (allowing columns to be omitted from
GROUP BY) only when a table\*(Aqs primary key is included in the
GROUP BY
list\&. The SQL standard specifies additional conditions that should be recognized\&.
.SS "LIMIT and OFFSET"
.PP
The clauses
LIMIT
and
OFFSET
are
PostgreSQL\-specific syntax, also used by
MySQL\&. The SQL:2008 standard has introduced the clauses
OFFSET \&.\&.\&. FETCH {FIRST|NEXT} \&.\&.\&.
for the same functionality, as shown above in
LIMIT Clause\&. This syntax is also used by
IBM DB2\&. (Applications written for
Oracle
frequently use a workaround involving the automatically generated
rownum
column, which is not available in PostgreSQL, to implement the effects of these clauses\&.)
.SS "FOR NO KEY UPDATE, FOR UPDATE, FOR SHARE, FOR KEY SHARE"
.PP
Although
FOR UPDATE
appears in the SQL standard, the standard allows it only as an option of
\fBDECLARE CURSOR\fR\&.
PostgreSQL
allows it in any
\fBSELECT\fR
query as well as in sub\-\fBSELECT\fRs, but this is an extension\&. The
FOR NO KEY UPDATE,
FOR SHARE
and
FOR KEY SHARE
variants, as well as the
NOWAIT
and
SKIP LOCKED
options, do not appear in the standard\&.
.SS "Data\-Modifying Statements in WITH"
.PP
PostgreSQL
allows
\fBINSERT\fR,
\fBUPDATE\fR, and
\fBDELETE\fR
to be used as
WITH
queries\&. This is not found in the SQL standard\&.
.SS "Nonstandard Clauses"
.PP
DISTINCT ON ( \&.\&.\&. )
is an extension of the SQL standard\&.
.PP
ROWS FROM( \&.\&.\&. )
is an extension of the SQL standard\&.
.PP
The
MATERIALIZED
and
NOT MATERIALIZED
options of
WITH
are extensions of the SQL standard\&.