summaryrefslogtreecommitdiffstats
path: root/src/test/regress/expected/subselect.out
blob: 45c75eecc5f2e836aa56b117d8b6092e9a7ae595 (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
--
-- SUBSELECT
--
SELECT 1 AS one WHERE 1 IN (SELECT 1);
 one 
-----
   1
(1 row)

SELECT 1 AS zero WHERE 1 NOT IN (SELECT 1);
 zero 
------
(0 rows)

SELECT 1 AS zero WHERE 1 IN (SELECT 2);
 zero 
------
(0 rows)

-- Check grammar's handling of extra parens in assorted contexts
SELECT * FROM (SELECT 1 AS x) ss;
 x 
---
 1
(1 row)

SELECT * FROM ((SELECT 1 AS x)) ss;
 x 
---
 1
(1 row)

(SELECT 2) UNION SELECT 2;
 ?column? 
----------
        2
(1 row)

((SELECT 2)) UNION SELECT 2;
 ?column? 
----------
        2
(1 row)

SELECT ((SELECT 2) UNION SELECT 2);
 ?column? 
----------
        2
(1 row)

SELECT (((SELECT 2)) UNION SELECT 2);
 ?column? 
----------
        2
(1 row)

SELECT (SELECT ARRAY[1,2,3])[1];
 array 
-------
     1
(1 row)

SELECT ((SELECT ARRAY[1,2,3]))[2];
 array 
-------
     2
(1 row)

SELECT (((SELECT ARRAY[1,2,3])))[3];
 array 
-------
     3
(1 row)

-- Set up some simple test tables
CREATE TABLE SUBSELECT_TBL (
  f1 integer,
  f2 integer,
  f3 float
);
INSERT INTO SUBSELECT_TBL VALUES (1, 2, 3);
INSERT INTO SUBSELECT_TBL VALUES (2, 3, 4);
INSERT INTO SUBSELECT_TBL VALUES (3, 4, 5);
INSERT INTO SUBSELECT_TBL VALUES (1, 1, 1);
INSERT INTO SUBSELECT_TBL VALUES (2, 2, 2);
INSERT INTO SUBSELECT_TBL VALUES (3, 3, 3);
INSERT INTO SUBSELECT_TBL VALUES (6, 7, 8);
INSERT INTO SUBSELECT_TBL VALUES (8, 9, NULL);
SELECT * FROM SUBSELECT_TBL;
 f1 | f2 | f3 
----+----+----
  1 |  2 |  3
  2 |  3 |  4
  3 |  4 |  5
  1 |  1 |  1
  2 |  2 |  2
  3 |  3 |  3
  6 |  7 |  8
  8 |  9 |   
(8 rows)

-- Uncorrelated subselects
SELECT f1 AS "Constant Select" FROM SUBSELECT_TBL
  WHERE f1 IN (SELECT 1);
 Constant Select 
-----------------
               1
               1
(2 rows)

SELECT f1 AS "Uncorrelated Field" FROM SUBSELECT_TBL
  WHERE f1 IN (SELECT f2 FROM SUBSELECT_TBL);
 Uncorrelated Field 
--------------------
                  1
                  2
                  3
                  1
                  2
                  3
(6 rows)

SELECT f1 AS "Uncorrelated Field" FROM SUBSELECT_TBL
  WHERE f1 IN (SELECT f2 FROM SUBSELECT_TBL WHERE
    f2 IN (SELECT f1 FROM SUBSELECT_TBL));
 Uncorrelated Field 
--------------------
                  1
                  2
                  3
                  1
                  2
                  3
(6 rows)

SELECT f1, f2
  FROM SUBSELECT_TBL
  WHERE (f1, f2) NOT IN (SELECT f2, CAST(f3 AS int4) FROM SUBSELECT_TBL
                         WHERE f3 IS NOT NULL);
 f1 | f2 
----+----
  1 |  2
  6 |  7
  8 |  9
(3 rows)

-- Correlated subselects
SELECT f1 AS "Correlated Field", f2 AS "Second Field"
  FROM SUBSELECT_TBL upper
  WHERE f1 IN (SELECT f2 FROM SUBSELECT_TBL WHERE f1 = upper.f1);
 Correlated Field | Second Field 
------------------+--------------
                1 |            2
                2 |            3
                3 |            4
                1 |            1
                2 |            2
                3 |            3
(6 rows)

SELECT f1 AS "Correlated Field", f3 AS "Second Field"
  FROM SUBSELECT_TBL upper
  WHERE f1 IN
    (SELECT f2 FROM SUBSELECT_TBL WHERE CAST(upper.f2 AS float) = f3);
 Correlated Field | Second Field 
------------------+--------------
                2 |            4
                3 |            5
                1 |            1
                2 |            2
                3 |            3
(5 rows)

SELECT f1 AS "Correlated Field", f3 AS "Second Field"
  FROM SUBSELECT_TBL upper
  WHERE f3 IN (SELECT upper.f1 + f2 FROM SUBSELECT_TBL
               WHERE f2 = CAST(f3 AS integer));
 Correlated Field | Second Field 
------------------+--------------
                1 |            3
                2 |            4
                3 |            5
                6 |            8
(4 rows)

SELECT f1 AS "Correlated Field"
  FROM SUBSELECT_TBL
  WHERE (f1, f2) IN (SELECT f2, CAST(f3 AS int4) FROM SUBSELECT_TBL
                     WHERE f3 IS NOT NULL);
 Correlated Field 
------------------
                2
                3
                1
                2
                3
(5 rows)

--
-- Use some existing tables in the regression test
--
SELECT ss.f1 AS "Correlated Field", ss.f3 AS "Second Field"
  FROM SUBSELECT_TBL ss
  WHERE f1 NOT IN (SELECT f1+1 FROM INT4_TBL
                   WHERE f1 != ss.f1 AND f1 < 2147483647);
 Correlated Field | Second Field 
------------------+--------------
                2 |            4
                3 |            5
                2 |            2
                3 |            3
                6 |            8
                8 |             
(6 rows)

select q1, float8(count(*)) / (select count(*) from int8_tbl)
from int8_tbl group by q1 order by q1;
        q1        | ?column? 
------------------+----------
              123 |      0.4
 4567890123456789 |      0.6
(2 rows)

-- Unspecified-type literals in output columns should resolve as text
SELECT *, pg_typeof(f1) FROM
  (SELECT 'foo' AS f1 FROM generate_series(1,3)) ss ORDER BY 1;
 f1  | pg_typeof 
-----+-----------
 foo | text
 foo | text
 foo | text
(3 rows)

-- ... unless there's context to suggest differently
explain (verbose, costs off) select '42' union all select '43';
         QUERY PLAN         
----------------------------
 Append
   ->  Result
         Output: '42'::text
   ->  Result
         Output: '43'::text
(5 rows)

explain (verbose, costs off) select '42' union all select 43;
     QUERY PLAN     
--------------------
 Append
   ->  Result
         Output: 42
   ->  Result
         Output: 43
(5 rows)

-- check materialization of an initplan reference (bug #14524)
explain (verbose, costs off)
select 1 = all (select (select 1));
            QUERY PLAN             
-----------------------------------
 Result
   Output: (SubPlan 2)
   SubPlan 2
     ->  Materialize
           Output: ($0)
           InitPlan 1 (returns $0)
             ->  Result
                   Output: 1
           ->  Result
                 Output: $0
(10 rows)

select 1 = all (select (select 1));
 ?column? 
----------
 t
(1 row)

--
-- Check EXISTS simplification with LIMIT
--
explain (costs off)
select * from int4_tbl o where exists
  (select 1 from int4_tbl i where i.f1=o.f1 limit null);
             QUERY PLAN             
------------------------------------
 Hash Semi Join
   Hash Cond: (o.f1 = i.f1)
   ->  Seq Scan on int4_tbl o
   ->  Hash
         ->  Seq Scan on int4_tbl i
(5 rows)

explain (costs off)
select * from int4_tbl o where not exists
  (select 1 from int4_tbl i where i.f1=o.f1 limit 1);
             QUERY PLAN             
------------------------------------
 Hash Anti Join
   Hash Cond: (o.f1 = i.f1)
   ->  Seq Scan on int4_tbl o
   ->  Hash
         ->  Seq Scan on int4_tbl i
(5 rows)

explain (costs off)
select * from int4_tbl o where exists
  (select 1 from int4_tbl i where i.f1=o.f1 limit 0);
              QUERY PLAN              
--------------------------------------
 Seq Scan on int4_tbl o
   Filter: (SubPlan 1)
   SubPlan 1
     ->  Limit
           ->  Seq Scan on int4_tbl i
                 Filter: (f1 = o.f1)
(6 rows)

--
-- Test cases to catch unpleasant interactions between IN-join processing
-- and subquery pullup.
--
select count(*) from
  (select 1 from tenk1 a
   where unique1 IN (select hundred from tenk1 b)) ss;
 count 
-------
   100
(1 row)

select count(distinct ss.ten) from
  (select ten from tenk1 a
   where unique1 IN (select hundred from tenk1 b)) ss;
 count 
-------
    10
(1 row)

select count(*) from
  (select 1 from tenk1 a
   where unique1 IN (select distinct hundred from tenk1 b)) ss;
 count 
-------
   100
(1 row)

select count(distinct ss.ten) from
  (select ten from tenk1 a
   where unique1 IN (select distinct hundred from tenk1 b)) ss;
 count 
-------
    10
(1 row)

--
-- Test cases to check for overenthusiastic optimization of
-- "IN (SELECT DISTINCT ...)" and related cases.  Per example from
-- Luca Pireddu and Michael Fuhr.
--
CREATE TEMP TABLE foo (id integer);
CREATE TEMP TABLE bar (id1 integer, id2 integer);
INSERT INTO foo VALUES (1);
INSERT INTO bar VALUES (1, 1);
INSERT INTO bar VALUES (2, 2);
INSERT INTO bar VALUES (3, 1);
-- These cases require an extra level of distinct-ing above subquery s
SELECT * FROM foo WHERE id IN
    (SELECT id2 FROM (SELECT DISTINCT id1, id2 FROM bar) AS s);
 id 
----
  1
(1 row)

SELECT * FROM foo WHERE id IN
    (SELECT id2 FROM (SELECT id1,id2 FROM bar GROUP BY id1,id2) AS s);
 id 
----
  1
(1 row)

SELECT * FROM foo WHERE id IN
    (SELECT id2 FROM (SELECT id1, id2 FROM bar UNION
                      SELECT id1, id2 FROM bar) AS s);
 id 
----
  1
(1 row)

-- These cases do not
SELECT * FROM foo WHERE id IN
    (SELECT id2 FROM (SELECT DISTINCT ON (id2) id1, id2 FROM bar) AS s);
 id 
----
  1
(1 row)

SELECT * FROM foo WHERE id IN
    (SELECT id2 FROM (SELECT id2 FROM bar GROUP BY id2) AS s);
 id 
----
  1
(1 row)

SELECT * FROM foo WHERE id IN
    (SELECT id2 FROM (SELECT id2 FROM bar UNION
                      SELECT id2 FROM bar) AS s);
 id 
----
  1
(1 row)

--
-- Test case to catch problems with multiply nested sub-SELECTs not getting
-- recalculated properly.  Per bug report from Didier Moens.
--
CREATE TABLE orderstest (
    approver_ref integer,
    po_ref integer,
    ordercanceled boolean
);
INSERT INTO orderstest VALUES (1, 1, false);
INSERT INTO orderstest VALUES (66, 5, false);
INSERT INTO orderstest VALUES (66, 6, false);
INSERT INTO orderstest VALUES (66, 7, false);
INSERT INTO orderstest VALUES (66, 1, true);
INSERT INTO orderstest VALUES (66, 8, false);
INSERT INTO orderstest VALUES (66, 1, false);
INSERT INTO orderstest VALUES (77, 1, false);
INSERT INTO orderstest VALUES (1, 1, false);
INSERT INTO orderstest VALUES (66, 1, false);
INSERT INTO orderstest VALUES (1, 1, false);
CREATE VIEW orders_view AS
SELECT *,
(SELECT CASE
   WHEN ord.approver_ref=1 THEN '---' ELSE 'Approved'
 END) AS "Approved",
(SELECT CASE
 WHEN ord.ordercanceled
 THEN 'Canceled'
 ELSE
  (SELECT CASE
		WHEN ord.po_ref=1
		THEN
		 (SELECT CASE
				WHEN ord.approver_ref=1
				THEN '---'
				ELSE 'Approved'
			END)
		ELSE 'PO'
	END)
END) AS "Status",
(CASE
 WHEN ord.ordercanceled
 THEN 'Canceled'
 ELSE
  (CASE
		WHEN ord.po_ref=1
		THEN
		 (CASE
				WHEN ord.approver_ref=1
				THEN '---'
				ELSE 'Approved'
			END)
		ELSE 'PO'
	END)
END) AS "Status_OK"
FROM orderstest ord;
SELECT * FROM orders_view;
 approver_ref | po_ref | ordercanceled | Approved |  Status  | Status_OK 
--------------+--------+---------------+----------+----------+-----------
            1 |      1 | f             | ---      | ---      | ---
           66 |      5 | f             | Approved | PO       | PO
           66 |      6 | f             | Approved | PO       | PO
           66 |      7 | f             | Approved | PO       | PO
           66 |      1 | t             | Approved | Canceled | Canceled
           66 |      8 | f             | Approved | PO       | PO
           66 |      1 | f             | Approved | Approved | Approved
           77 |      1 | f             | Approved | Approved | Approved
            1 |      1 | f             | ---      | ---      | ---
           66 |      1 | f             | Approved | Approved | Approved
            1 |      1 | f             | ---      | ---      | ---
(11 rows)

DROP TABLE orderstest cascade;
NOTICE:  drop cascades to view orders_view
--
-- Test cases to catch situations where rule rewriter fails to propagate
-- hasSubLinks flag correctly.  Per example from Kyle Bateman.
--
create temp table parts (
    partnum     text,
    cost        float8
);
create temp table shipped (
    ttype       char(2),
    ordnum      int4,
    partnum     text,
    value       float8
);
create temp view shipped_view as
    select * from shipped where ttype = 'wt';
create rule shipped_view_insert as on insert to shipped_view do instead
    insert into shipped values('wt', new.ordnum, new.partnum, new.value);
insert into parts (partnum, cost) values (1, 1234.56);
insert into shipped_view (ordnum, partnum, value)
    values (0, 1, (select cost from parts where partnum = '1'));
select * from shipped_view;
 ttype | ordnum | partnum |  value  
-------+--------+---------+---------
 wt    |      0 | 1       | 1234.56
(1 row)

create rule shipped_view_update as on update to shipped_view do instead
    update shipped set partnum = new.partnum, value = new.value
        where ttype = new.ttype and ordnum = new.ordnum;
update shipped_view set value = 11
    from int4_tbl a join int4_tbl b
      on (a.f1 = (select f1 from int4_tbl c where c.f1=b.f1))
    where ordnum = a.f1;
select * from shipped_view;
 ttype | ordnum | partnum | value 
-------+--------+---------+-------
 wt    |      0 | 1       |    11
(1 row)

select f1, ss1 as relabel from
    (select *, (select sum(f1) from int4_tbl b where f1 >= a.f1) as ss1
     from int4_tbl a) ss;
     f1      |  relabel   
-------------+------------
           0 | 2147607103
      123456 | 2147607103
     -123456 | 2147483647
  2147483647 | 2147483647
 -2147483647 |          0
(5 rows)

--
-- Test cases involving PARAM_EXEC parameters and min/max index optimizations.
-- Per bug report from David Sanchez i Gregori.
--
select * from (
  select max(unique1) from tenk1 as a
  where exists (select 1 from tenk1 as b where b.thousand = a.unique2)
) ss;
 max  
------
 9997
(1 row)

select * from (
  select min(unique1) from tenk1 as a
  where not exists (select 1 from tenk1 as b where b.unique2 = 10000)
) ss;
 min 
-----
   0
(1 row)

--
-- Test that an IN implemented using a UniquePath does unique-ification
-- with the right semantics, as per bug #4113.  (Unfortunately we have
-- no simple way to ensure that this test case actually chooses that type
-- of plan, but it does in releases 7.4-8.3.  Note that an ordering difference
-- here might mean that some other plan type is being used, rendering the test
-- pointless.)
--
create temp table numeric_table (num_col numeric);
insert into numeric_table values (1), (1.000000000000000000001), (2), (3);
create temp table float_table (float_col float8);
insert into float_table values (1), (2), (3);
select * from float_table
  where float_col in (select num_col from numeric_table);
 float_col 
-----------
         1
         2
         3
(3 rows)

select * from numeric_table
  where num_col in (select float_col from float_table);
         num_col         
-------------------------
                       1
 1.000000000000000000001
                       2
                       3
(4 rows)

--
-- Test case for bug #4290: bogus calculation of subplan param sets
--
create temp table ta (id int primary key, val int);
insert into ta values(1,1);
insert into ta values(2,2);
create temp table tb (id int primary key, aval int);
insert into tb values(1,1);
insert into tb values(2,1);
insert into tb values(3,2);
insert into tb values(4,2);
create temp table tc (id int primary key, aid int);
insert into tc values(1,1);
insert into tc values(2,2);
select
  ( select min(tb.id) from tb
    where tb.aval = (select ta.val from ta where ta.id = tc.aid) ) as min_tb_id
from tc;
 min_tb_id 
-----------
         1
         3
(2 rows)

--
-- Test case for 8.3 "failed to locate grouping columns" bug
--
create temp table t1 (f1 numeric(14,0), f2 varchar(30));
select * from
  (select distinct f1, f2, (select f2 from t1 x where x.f1 = up.f1) as fs
   from t1 up) ss
group by f1,f2,fs;
 f1 | f2 | fs 
----+----+----
(0 rows)

--
-- Test case for bug #5514 (mishandling of whole-row Vars in subselects)
--
create temp table table_a(id integer);
insert into table_a values (42);
create temp view view_a as select * from table_a;
select view_a from view_a;
 view_a 
--------
 (42)
(1 row)

select (select view_a) from view_a;
 view_a 
--------
 (42)
(1 row)

select (select (select view_a)) from view_a;
 view_a 
--------
 (42)
(1 row)

select (select (a.*)::text) from view_a a;
  a   
------
 (42)
(1 row)

--
-- Check that whole-row Vars reading the result of a subselect don't include
-- any junk columns therein
--
select q from (select max(f1) from int4_tbl group by f1 order by f1) q;
       q       
---------------
 (-2147483647)
 (-123456)
 (0)
 (123456)
 (2147483647)
(5 rows)

with q as (select max(f1) from int4_tbl group by f1 order by f1)
  select q from q;
       q       
---------------
 (-2147483647)
 (-123456)
 (0)
 (123456)
 (2147483647)
(5 rows)

--
-- Test case for sublinks pulled up into joinaliasvars lists in an
-- inherited update/delete query
--
begin;  --  this shouldn't delete anything, but be safe
delete from road
where exists (
  select 1
  from
    int4_tbl cross join
    ( select f1, array(select q1 from int8_tbl) as arr
      from text_tbl ) ss
  where road.name = ss.f1 );
rollback;
--
-- Test case for sublinks pushed down into subselects via join alias expansion
--
select
  (select sq1) as qq1
from
  (select exists(select 1 from int4_tbl where f1 = q2) as sq1, 42 as dummy
   from int8_tbl) sq0
  join
  int4_tbl i4 on dummy = i4.f1;
 qq1 
-----
(0 rows)

--
-- Test case for subselect within UPDATE of INSERT...ON CONFLICT DO UPDATE
--
create temp table upsert(key int4 primary key, val text);
insert into upsert values(1, 'val') on conflict (key) do update set val = 'not seen';
insert into upsert values(1, 'val') on conflict (key) do update set val = 'seen with subselect ' || (select f1 from int4_tbl where f1 != 0 limit 1)::text;
select * from upsert;
 key |            val             
-----+----------------------------
   1 | seen with subselect 123456
(1 row)

with aa as (select 'int4_tbl' u from int4_tbl limit 1)
insert into upsert values (1, 'x'), (999, 'y')
on conflict (key) do update set val = (select u from aa)
returning *;
 key |   val    
-----+----------
   1 | int4_tbl
 999 | y
(2 rows)

--
-- Test case for cross-type partial matching in hashed subplan (bug #7597)
--
create temp table outer_7597 (f1 int4, f2 int4);
insert into outer_7597 values (0, 0);
insert into outer_7597 values (1, 0);
insert into outer_7597 values (0, null);
insert into outer_7597 values (1, null);
create temp table inner_7597(c1 int8, c2 int8);
insert into inner_7597 values(0, null);
select * from outer_7597 where (f1, f2) not in (select * from inner_7597);
 f1 | f2 
----+----
  1 |  0
  1 |   
(2 rows)

--
-- Similar test case using text that verifies that collation
-- information is passed through by execTuplesEqual() in nodeSubplan.c
-- (otherwise it would error in texteq())
--
create temp table outer_text (f1 text, f2 text);
insert into outer_text values ('a', 'a');
insert into outer_text values ('b', 'a');
insert into outer_text values ('a', null);
insert into outer_text values ('b', null);
create temp table inner_text (c1 text, c2 text);
insert into inner_text values ('a', null);
insert into inner_text values ('123', '456');
select * from outer_text where (f1, f2) not in (select * from inner_text);
 f1 | f2 
----+----
 b  | a
 b  | 
(2 rows)

--
-- Another test case for cross-type hashed subplans: comparison of
-- inner-side values must be done with appropriate operator
--
explain (verbose, costs off)
select 'foo'::text in (select 'bar'::name union all select 'bar'::name);
             QUERY PLAN              
-------------------------------------
 Result
   Output: (hashed SubPlan 1)
   SubPlan 1
     ->  Append
           ->  Result
                 Output: 'bar'::name
           ->  Result
                 Output: 'bar'::name
(8 rows)

select 'foo'::text in (select 'bar'::name union all select 'bar'::name);
 ?column? 
----------
 f
(1 row)

--
-- Test that we don't try to hash nested records (bug #17363)
-- (Hashing could be supported, but for now we don't)
--
explain (verbose, costs off)
select row(row(row(1))) = any (select row(row(1)));
                QUERY PLAN                 
-------------------------------------------
 Result
   Output: (SubPlan 1)
   SubPlan 1
     ->  Materialize
           Output: '("(1)")'::record
           ->  Result
                 Output: '("(1)")'::record
(7 rows)

select row(row(row(1))) = any (select row(row(1)));
 ?column? 
----------
 t
(1 row)

--
-- Test case for premature memory release during hashing of subplan output
--
select '1'::text in (select '1'::name union all select '1'::name);
 ?column? 
----------
 t
(1 row)

--
-- Test that we don't try to use a hashed subplan if the simplified
-- testexpr isn't of the right shape
--
-- this fails by default, of course
select * from int8_tbl where q1 in (select c1 from inner_text);
ERROR:  operator does not exist: bigint = text
LINE 1: select * from int8_tbl where q1 in (select c1 from inner_tex...
                                        ^
HINT:  No operator matches the given name and argument types. You might need to add explicit type casts.
begin;
-- make an operator to allow it to succeed
create function bogus_int8_text_eq(int8, text) returns boolean
language sql as 'select $1::text = $2';
create operator = (procedure=bogus_int8_text_eq, leftarg=int8, rightarg=text);
explain (costs off)
select * from int8_tbl where q1 in (select c1 from inner_text);
           QUERY PLAN           
--------------------------------
 Seq Scan on int8_tbl
   Filter: (hashed SubPlan 1)
   SubPlan 1
     ->  Seq Scan on inner_text
(4 rows)

select * from int8_tbl where q1 in (select c1 from inner_text);
 q1  |        q2        
-----+------------------
 123 |              456
 123 | 4567890123456789
(2 rows)

-- inlining of this function results in unusual number of hash clauses,
-- which we can still cope with
create or replace function bogus_int8_text_eq(int8, text) returns boolean
language sql as 'select $1::text = $2 and $1::text = $2';
explain (costs off)
select * from int8_tbl where q1 in (select c1 from inner_text);
           QUERY PLAN           
--------------------------------
 Seq Scan on int8_tbl
   Filter: (hashed SubPlan 1)
   SubPlan 1
     ->  Seq Scan on inner_text
(4 rows)

select * from int8_tbl where q1 in (select c1 from inner_text);
 q1  |        q2        
-----+------------------
 123 |              456
 123 | 4567890123456789
(2 rows)

-- inlining of this function causes LHS and RHS to be switched,
-- which we can't cope with, so hashing should be abandoned
create or replace function bogus_int8_text_eq(int8, text) returns boolean
language sql as 'select $2 = $1::text';
explain (costs off)
select * from int8_tbl where q1 in (select c1 from inner_text);
              QUERY PLAN              
--------------------------------------
 Seq Scan on int8_tbl
   Filter: (SubPlan 1)
   SubPlan 1
     ->  Materialize
           ->  Seq Scan on inner_text
(5 rows)

select * from int8_tbl where q1 in (select c1 from inner_text);
 q1  |        q2        
-----+------------------
 123 |              456
 123 | 4567890123456789
(2 rows)

rollback;  -- to get rid of the bogus operator
--
-- Test resolution of hashed vs non-hashed implementation of EXISTS subplan
--
explain (costs off)
select count(*) from tenk1 t
where (exists(select 1 from tenk1 k where k.unique1 = t.unique2) or ten < 0);
                          QUERY PLAN                          
--------------------------------------------------------------
 Aggregate
   ->  Seq Scan on tenk1 t
         Filter: ((hashed SubPlan 2) OR (ten < 0))
         SubPlan 2
           ->  Index Only Scan using tenk1_unique1 on tenk1 k
(5 rows)

select count(*) from tenk1 t
where (exists(select 1 from tenk1 k where k.unique1 = t.unique2) or ten < 0);
 count 
-------
 10000
(1 row)

explain (costs off)
select count(*) from tenk1 t
where (exists(select 1 from tenk1 k where k.unique1 = t.unique2) or ten < 0)
  and thousand = 1;
                          QUERY PLAN                          
--------------------------------------------------------------
 Aggregate
   ->  Bitmap Heap Scan on tenk1 t
         Recheck Cond: (thousand = 1)
         Filter: ((SubPlan 1) OR (ten < 0))
         ->  Bitmap Index Scan on tenk1_thous_tenthous
               Index Cond: (thousand = 1)
         SubPlan 1
           ->  Index Only Scan using tenk1_unique1 on tenk1 k
                 Index Cond: (unique1 = t.unique2)
(9 rows)

select count(*) from tenk1 t
where (exists(select 1 from tenk1 k where k.unique1 = t.unique2) or ten < 0)
  and thousand = 1;
 count 
-------
    10
(1 row)

-- It's possible for the same EXISTS to get resolved both ways
create temp table exists_tbl (c1 int, c2 int, c3 int) partition by list (c1);
create temp table exists_tbl_null partition of exists_tbl for values in (null);
create temp table exists_tbl_def partition of exists_tbl default;
insert into exists_tbl select x, x/2, x+1 from generate_series(0,10) x;
analyze exists_tbl;
explain (costs off)
select * from exists_tbl t1
  where (exists(select 1 from exists_tbl t2 where t1.c1 = t2.c2) or c3 < 0);
                      QUERY PLAN                      
------------------------------------------------------
 Append
   ->  Seq Scan on exists_tbl_null t1_1
         Filter: ((SubPlan 1) OR (c3 < 0))
         SubPlan 1
           ->  Append
                 ->  Seq Scan on exists_tbl_null t2_1
                       Filter: (t1_1.c1 = c2)
                 ->  Seq Scan on exists_tbl_def t2_2
                       Filter: (t1_1.c1 = c2)
   ->  Seq Scan on exists_tbl_def t1_2
         Filter: ((hashed SubPlan 2) OR (c3 < 0))
         SubPlan 2
           ->  Append
                 ->  Seq Scan on exists_tbl_null t2_4
                 ->  Seq Scan on exists_tbl_def t2_5
(15 rows)

select * from exists_tbl t1
  where (exists(select 1 from exists_tbl t2 where t1.c1 = t2.c2) or c3 < 0);
 c1 | c2 | c3 
----+----+----
  0 |  0 |  1
  1 |  0 |  2
  2 |  1 |  3
  3 |  1 |  4
  4 |  2 |  5
  5 |  2 |  6
(6 rows)

--
-- Test case for planner bug with nested EXISTS handling
--
select a.thousand from tenk1 a, tenk1 b
where a.thousand = b.thousand
  and exists ( select 1 from tenk1 c where b.hundred = c.hundred
                   and not exists ( select 1 from tenk1 d
                                    where a.thousand = d.thousand ) );
 thousand 
----------
(0 rows)

--
-- Check that nested sub-selects are not pulled up if they contain volatiles
--
explain (verbose, costs off)
  select x, x from
    (select (select now()) as x from (values(1),(2)) v(y)) ss;
        QUERY PLAN         
---------------------------
 Values Scan on "*VALUES*"
   Output: $0, $1
   InitPlan 1 (returns $0)
     ->  Result
           Output: now()
   InitPlan 2 (returns $1)
     ->  Result
           Output: now()
(8 rows)

explain (verbose, costs off)
  select x, x from
    (select (select random()) as x from (values(1),(2)) v(y)) ss;
            QUERY PLAN            
----------------------------------
 Subquery Scan on ss
   Output: ss.x, ss.x
   ->  Values Scan on "*VALUES*"
         Output: $0
         InitPlan 1 (returns $0)
           ->  Result
                 Output: random()
(7 rows)

explain (verbose, costs off)
  select x, x from
    (select (select now() where y=y) as x from (values(1),(2)) v(y)) ss;
                              QUERY PLAN                              
----------------------------------------------------------------------
 Values Scan on "*VALUES*"
   Output: (SubPlan 1), (SubPlan 2)
   SubPlan 1
     ->  Result
           Output: now()
           One-Time Filter: ("*VALUES*".column1 = "*VALUES*".column1)
   SubPlan 2
     ->  Result
           Output: now()
           One-Time Filter: ("*VALUES*".column1 = "*VALUES*".column1)
(10 rows)

explain (verbose, costs off)
  select x, x from
    (select (select random() where y=y) as x from (values(1),(2)) v(y)) ss;
                                 QUERY PLAN                                 
----------------------------------------------------------------------------
 Subquery Scan on ss
   Output: ss.x, ss.x
   ->  Values Scan on "*VALUES*"
         Output: (SubPlan 1)
         SubPlan 1
           ->  Result
                 Output: random()
                 One-Time Filter: ("*VALUES*".column1 = "*VALUES*".column1)
(8 rows)

--
-- Test rescan of a hashed subplan (the use of random() is to prevent the
-- sub-select from being pulled up, which would result in not hashing)
--
explain (verbose, costs off)
select sum(ss.tst::int) from
  onek o cross join lateral (
  select i.ten in (select f1 from int4_tbl where f1 <= o.hundred) as tst,
         random() as r
  from onek i where i.unique1 = o.unique1 ) ss
where o.ten = 0;
                                                                                         QUERY PLAN                                                                                          
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Aggregate
   Output: sum((((hashed SubPlan 1)))::integer)
   ->  Nested Loop
         Output: ((hashed SubPlan 1))
         ->  Seq Scan on public.onek o
               Output: o.unique1, o.unique2, o.two, o.four, o.ten, o.twenty, o.hundred, o.thousand, o.twothousand, o.fivethous, o.tenthous, o.odd, o.even, o.stringu1, o.stringu2, o.string4
               Filter: (o.ten = 0)
         ->  Index Scan using onek_unique1 on public.onek i
               Output: (hashed SubPlan 1), random()
               Index Cond: (i.unique1 = o.unique1)
               SubPlan 1
                 ->  Seq Scan on public.int4_tbl
                       Output: int4_tbl.f1
                       Filter: (int4_tbl.f1 <= $0)
(14 rows)

select sum(ss.tst::int) from
  onek o cross join lateral (
  select i.ten in (select f1 from int4_tbl where f1 <= o.hundred) as tst,
         random() as r
  from onek i where i.unique1 = o.unique1 ) ss
where o.ten = 0;
 sum 
-----
 100
(1 row)

--
-- Test rescan of a SetOp node
--
explain (costs off)
select count(*) from
  onek o cross join lateral (
    select * from onek i1 where i1.unique1 = o.unique1
    except
    select * from onek i2 where i2.unique1 = o.unique2
  ) ss
where o.ten = 1;
                                  QUERY PLAN                                  
------------------------------------------------------------------------------
 Aggregate
   ->  Nested Loop
         ->  Seq Scan on onek o
               Filter: (ten = 1)
         ->  Subquery Scan on ss
               ->  HashSetOp Except
                     ->  Append
                           ->  Subquery Scan on "*SELECT* 1"
                                 ->  Index Scan using onek_unique1 on onek i1
                                       Index Cond: (unique1 = o.unique1)
                           ->  Subquery Scan on "*SELECT* 2"
                                 ->  Index Scan using onek_unique1 on onek i2
                                       Index Cond: (unique1 = o.unique2)
(13 rows)

select count(*) from
  onek o cross join lateral (
    select * from onek i1 where i1.unique1 = o.unique1
    except
    select * from onek i2 where i2.unique1 = o.unique2
  ) ss
where o.ten = 1;
 count 
-------
   100
(1 row)

--
-- Test rescan of a RecursiveUnion node
--
explain (costs off)
select sum(o.four), sum(ss.a) from
  onek o cross join lateral (
    with recursive x(a) as
      (select o.four as a
       union
       select a + 1 from x
       where a < 10)
    select * from x
  ) ss
where o.ten = 1;
                       QUERY PLAN                        
---------------------------------------------------------
 Aggregate
   ->  Nested Loop
         ->  Seq Scan on onek o
               Filter: (ten = 1)
         ->  Memoize
               Cache Key: o.four
               Cache Mode: binary
               ->  CTE Scan on x
                     CTE x
                       ->  Recursive Union
                             ->  Result
                             ->  WorkTable Scan on x x_1
                                   Filter: (a < 10)
(13 rows)

select sum(o.four), sum(ss.a) from
  onek o cross join lateral (
    with recursive x(a) as
      (select o.four as a
       union
       select a + 1 from x
       where a < 10)
    select * from x
  ) ss
where o.ten = 1;
 sum  | sum  
------+------
 1700 | 5350
(1 row)

--
-- Check we don't misoptimize a NOT IN where the subquery returns no rows.
--
create temp table notinouter (a int);
create temp table notininner (b int not null);
insert into notinouter values (null), (1);
select * from notinouter where a not in (select b from notininner);
 a 
---
  
 1
(2 rows)

--
-- Check we behave sanely in corner case of empty SELECT list (bug #8648)
--
create temp table nocolumns();
select exists(select * from nocolumns);
 exists 
--------
 f
(1 row)

--
-- Check behavior with a SubPlan in VALUES (bug #14924)
--
select val.x
  from generate_series(1,10) as s(i),
  lateral (
    values ((select s.i + 1)), (s.i + 101)
  ) as val(x)
where s.i < 10 and (select val.x) < 110;
  x  
-----
   2
 102
   3
 103
   4
 104
   5
 105
   6
 106
   7
 107
   8
 108
   9
 109
  10
(17 rows)

-- another variant of that (bug #16213)
explain (verbose, costs off)
select * from
(values
  (3 not in (select * from (values (1), (2)) ss1)),
  (false)
) ss;
               QUERY PLAN               
----------------------------------------
 Values Scan on "*VALUES*"
   Output: "*VALUES*".column1
   SubPlan 1
     ->  Values Scan on "*VALUES*_1"
           Output: "*VALUES*_1".column1
(5 rows)

select * from
(values
  (3 not in (select * from (values (1), (2)) ss1)),
  (false)
) ss;
 column1 
---------
 t
 f
(2 rows)

--
-- Check sane behavior with nested IN SubLinks
--
explain (verbose, costs off)
select * from int4_tbl where
  (case when f1 in (select unique1 from tenk1 a) then f1 else null end) in
  (select ten from tenk1 b);
                                                                                      QUERY PLAN                                                                                       
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Nested Loop Semi Join
   Output: int4_tbl.f1
   Join Filter: (CASE WHEN (hashed SubPlan 1) THEN int4_tbl.f1 ELSE NULL::integer END = b.ten)
   ->  Seq Scan on public.int4_tbl
         Output: int4_tbl.f1
   ->  Seq Scan on public.tenk1 b
         Output: b.unique1, b.unique2, b.two, b.four, b.ten, b.twenty, b.hundred, b.thousand, b.twothousand, b.fivethous, b.tenthous, b.odd, b.even, b.stringu1, b.stringu2, b.string4
   SubPlan 1
     ->  Index Only Scan using tenk1_unique1 on public.tenk1 a
           Output: a.unique1
(10 rows)

select * from int4_tbl where
  (case when f1 in (select unique1 from tenk1 a) then f1 else null end) in
  (select ten from tenk1 b);
 f1 
----
  0
(1 row)

--
-- Check for incorrect optimization when IN subquery contains a SRF
--
explain (verbose, costs off)
select * from int4_tbl o where (f1, f1) in
  (select f1, generate_series(1,50) / 10 g from int4_tbl i group by f1);
                            QUERY PLAN                             
-------------------------------------------------------------------
 Nested Loop Semi Join
   Output: o.f1
   Join Filter: (o.f1 = "ANY_subquery".f1)
   ->  Seq Scan on public.int4_tbl o
         Output: o.f1
   ->  Materialize
         Output: "ANY_subquery".f1, "ANY_subquery".g
         ->  Subquery Scan on "ANY_subquery"
               Output: "ANY_subquery".f1, "ANY_subquery".g
               Filter: ("ANY_subquery".f1 = "ANY_subquery".g)
               ->  Result
                     Output: i.f1, ((generate_series(1, 50)) / 10)
                     ->  ProjectSet
                           Output: generate_series(1, 50), i.f1
                           ->  HashAggregate
                                 Output: i.f1
                                 Group Key: i.f1
                                 ->  Seq Scan on public.int4_tbl i
                                       Output: i.f1
(19 rows)

select * from int4_tbl o where (f1, f1) in
  (select f1, generate_series(1,50) / 10 g from int4_tbl i group by f1);
 f1 
----
  0
(1 row)

--
-- check for over-optimization of whole-row Var referencing an Append plan
--
select (select q from
         (select 1,2,3 where f1 > 0
          union all
          select 4,5,6.0 where f1 <= 0
         ) q )
from int4_tbl;
     q     
-----------
 (4,5,6.0)
 (1,2,3)
 (4,5,6.0)
 (1,2,3)
 (4,5,6.0)
(5 rows)

--
-- Check for sane handling of a lateral reference in a subquery's quals
-- (most of the complication here is to prevent the test case from being
-- flattened too much)
--
explain (verbose, costs off)
select * from
    int4_tbl i4,
    lateral (
        select i4.f1 > 1 as b, 1 as id
        from (select random() order by 1) as t1
      union all
        select true as b, 2 as id
    ) as t2
where b and f1 >= 0;
                 QUERY PLAN                 
--------------------------------------------
 Nested Loop
   Output: i4.f1, ((i4.f1 > 1)), (1)
   ->  Seq Scan on public.int4_tbl i4
         Output: i4.f1
         Filter: (i4.f1 >= 0)
   ->  Append
         ->  Subquery Scan on t1
               Output: (i4.f1 > 1), 1
               Filter: (i4.f1 > 1)
               ->  Sort
                     Output: (random())
                     Sort Key: (random())
                     ->  Result
                           Output: random()
         ->  Result
               Output: true, 2
(16 rows)

select * from
    int4_tbl i4,
    lateral (
        select i4.f1 > 1 as b, 1 as id
        from (select random() order by 1) as t1
      union all
        select true as b, 2 as id
    ) as t2
where b and f1 >= 0;
     f1     | b | id 
------------+---+----
          0 | t |  2
     123456 | t |  1
     123456 | t |  2
 2147483647 | t |  1
 2147483647 | t |  2
(5 rows)

--
-- Check that volatile quals aren't pushed down past a DISTINCT:
-- nextval() should not be called more than the nominal number of times
--
create temp sequence ts1;
select * from
  (select distinct ten from tenk1) ss
  where ten < 10 + nextval('ts1')
  order by 1;
 ten 
-----
   0
   1
   2
   3
   4
   5
   6
   7
   8
   9
(10 rows)

select nextval('ts1');
 nextval 
---------
      11
(1 row)

--
-- Check that volatile quals aren't pushed down past a set-returning function;
-- while a nonvolatile qual can be, if it doesn't reference the SRF.
--
create function tattle(x int, y int) returns bool
volatile language plpgsql as $$
begin
  raise notice 'x = %, y = %', x, y;
  return x > y;
end$$;
explain (verbose, costs off)
select * from
  (select 9 as x, unnest(array[1,2,3,11,12,13]) as u) ss
  where tattle(x, 8);
                        QUERY PLAN                        
----------------------------------------------------------
 Subquery Scan on ss
   Output: ss.x, ss.u
   Filter: tattle(ss.x, 8)
   ->  ProjectSet
         Output: 9, unnest('{1,2,3,11,12,13}'::integer[])
         ->  Result
(6 rows)

select * from
  (select 9 as x, unnest(array[1,2,3,11,12,13]) as u) ss
  where tattle(x, 8);
NOTICE:  x = 9, y = 8
NOTICE:  x = 9, y = 8
NOTICE:  x = 9, y = 8
NOTICE:  x = 9, y = 8
NOTICE:  x = 9, y = 8
NOTICE:  x = 9, y = 8
 x | u  
---+----
 9 |  1
 9 |  2
 9 |  3
 9 | 11
 9 | 12
 9 | 13
(6 rows)

-- if we pretend it's stable, we get different results:
alter function tattle(x int, y int) stable;
explain (verbose, costs off)
select * from
  (select 9 as x, unnest(array[1,2,3,11,12,13]) as u) ss
  where tattle(x, 8);
                     QUERY PLAN                     
----------------------------------------------------
 ProjectSet
   Output: 9, unnest('{1,2,3,11,12,13}'::integer[])
   ->  Result
         One-Time Filter: tattle(9, 8)
(4 rows)

select * from
  (select 9 as x, unnest(array[1,2,3,11,12,13]) as u) ss
  where tattle(x, 8);
NOTICE:  x = 9, y = 8
 x | u  
---+----
 9 |  1
 9 |  2
 9 |  3
 9 | 11
 9 | 12
 9 | 13
(6 rows)

-- although even a stable qual should not be pushed down if it references SRF
explain (verbose, costs off)
select * from
  (select 9 as x, unnest(array[1,2,3,11,12,13]) as u) ss
  where tattle(x, u);
                        QUERY PLAN                        
----------------------------------------------------------
 Subquery Scan on ss
   Output: ss.x, ss.u
   Filter: tattle(ss.x, ss.u)
   ->  ProjectSet
         Output: 9, unnest('{1,2,3,11,12,13}'::integer[])
         ->  Result
(6 rows)

select * from
  (select 9 as x, unnest(array[1,2,3,11,12,13]) as u) ss
  where tattle(x, u);
NOTICE:  x = 9, y = 1
NOTICE:  x = 9, y = 2
NOTICE:  x = 9, y = 3
NOTICE:  x = 9, y = 11
NOTICE:  x = 9, y = 12
NOTICE:  x = 9, y = 13
 x | u 
---+---
 9 | 1
 9 | 2
 9 | 3
(3 rows)

drop function tattle(x int, y int);
--
-- Test that LIMIT can be pushed to SORT through a subquery that just projects
-- columns.  We check for that having happened by looking to see if EXPLAIN
-- ANALYZE shows that a top-N sort was used.  We must suppress or filter away
-- all the non-invariant parts of the EXPLAIN ANALYZE output.
--
create table sq_limit (pk int primary key, c1 int, c2 int);
insert into sq_limit values
    (1, 1, 1),
    (2, 2, 2),
    (3, 3, 3),
    (4, 4, 4),
    (5, 1, 1),
    (6, 2, 2),
    (7, 3, 3),
    (8, 4, 4);
create function explain_sq_limit() returns setof text language plpgsql as
$$
declare ln text;
begin
    for ln in
        explain (analyze, summary off, timing off, costs off)
        select * from (select pk,c2 from sq_limit order by c1,pk) as x limit 3
    loop
        ln := regexp_replace(ln, 'Memory: \S*',  'Memory: xxx');
        return next ln;
    end loop;
end;
$$;
select * from explain_sq_limit();
                        explain_sq_limit                        
----------------------------------------------------------------
 Limit (actual rows=3 loops=1)
   ->  Subquery Scan on x (actual rows=3 loops=1)
         ->  Sort (actual rows=3 loops=1)
               Sort Key: sq_limit.c1, sq_limit.pk
               Sort Method: top-N heapsort  Memory: xxx
               ->  Seq Scan on sq_limit (actual rows=8 loops=1)
(6 rows)

select * from (select pk,c2 from sq_limit order by c1,pk) as x limit 3;
 pk | c2 
----+----
  1 |  1
  5 |  1
  2 |  2
(3 rows)

drop function explain_sq_limit();
drop table sq_limit;
--
-- Ensure that backward scan direction isn't propagated into
-- expression subqueries (bug #15336)
--
begin;
declare c1 scroll cursor for
 select * from generate_series(1,4) i
  where i <> all (values (2),(3));
move forward all in c1;
fetch backward all in c1;
 i 
---
 4
 1
(2 rows)

commit;
--
-- Tests for CTE inlining behavior
--
-- Basic subquery that can be inlined
explain (verbose, costs off)
with x as (select * from (select f1 from subselect_tbl) ss)
select * from x where f1 = 1;
            QUERY PLAN            
----------------------------------
 Seq Scan on public.subselect_tbl
   Output: subselect_tbl.f1
   Filter: (subselect_tbl.f1 = 1)
(3 rows)

-- Explicitly request materialization
explain (verbose, costs off)
with x as materialized (select * from (select f1 from subselect_tbl) ss)
select * from x where f1 = 1;
                QUERY PLAN                
------------------------------------------
 CTE Scan on x
   Output: x.f1
   Filter: (x.f1 = 1)
   CTE x
     ->  Seq Scan on public.subselect_tbl
           Output: subselect_tbl.f1
(6 rows)

-- Stable functions are safe to inline
explain (verbose, costs off)
with x as (select * from (select f1, now() from subselect_tbl) ss)
select * from x where f1 = 1;
            QUERY PLAN             
-----------------------------------
 Seq Scan on public.subselect_tbl
   Output: subselect_tbl.f1, now()
   Filter: (subselect_tbl.f1 = 1)
(3 rows)

-- Volatile functions prevent inlining
explain (verbose, costs off)
with x as (select * from (select f1, random() from subselect_tbl) ss)
select * from x where f1 = 1;
                  QUERY PLAN                  
----------------------------------------------
 CTE Scan on x
   Output: x.f1, x.random
   Filter: (x.f1 = 1)
   CTE x
     ->  Seq Scan on public.subselect_tbl
           Output: subselect_tbl.f1, random()
(6 rows)

-- SELECT FOR UPDATE cannot be inlined
explain (verbose, costs off)
with x as (select * from (select f1 from subselect_tbl for update) ss)
select * from x where f1 = 1;
                             QUERY PLAN                             
--------------------------------------------------------------------
 CTE Scan on x
   Output: x.f1
   Filter: (x.f1 = 1)
   CTE x
     ->  Subquery Scan on ss
           Output: ss.f1
           ->  LockRows
                 Output: subselect_tbl.f1, subselect_tbl.ctid
                 ->  Seq Scan on public.subselect_tbl
                       Output: subselect_tbl.f1, subselect_tbl.ctid
(10 rows)

-- Multiply-referenced CTEs are inlined only when requested
explain (verbose, costs off)
with x as (select * from (select f1, now() as n from subselect_tbl) ss)
select * from x, x x2 where x.n = x2.n;
                QUERY PLAN                 
-------------------------------------------
 Merge Join
   Output: x.f1, x.n, x2.f1, x2.n
   Merge Cond: (x.n = x2.n)
   CTE x
     ->  Seq Scan on public.subselect_tbl
           Output: subselect_tbl.f1, now()
   ->  Sort
         Output: x.f1, x.n
         Sort Key: x.n
         ->  CTE Scan on x
               Output: x.f1, x.n
   ->  Sort
         Output: x2.f1, x2.n
         Sort Key: x2.n
         ->  CTE Scan on x x2
               Output: x2.f1, x2.n
(16 rows)

explain (verbose, costs off)
with x as not materialized (select * from (select f1, now() as n from subselect_tbl) ss)
select * from x, x x2 where x.n = x2.n;
                                 QUERY PLAN                                 
----------------------------------------------------------------------------
 Result
   Output: subselect_tbl.f1, now(), subselect_tbl_1.f1, now()
   One-Time Filter: (now() = now())
   ->  Nested Loop
         Output: subselect_tbl.f1, subselect_tbl_1.f1
         ->  Seq Scan on public.subselect_tbl
               Output: subselect_tbl.f1, subselect_tbl.f2, subselect_tbl.f3
         ->  Materialize
               Output: subselect_tbl_1.f1
               ->  Seq Scan on public.subselect_tbl subselect_tbl_1
                     Output: subselect_tbl_1.f1
(11 rows)

-- Multiply-referenced CTEs can't be inlined if they contain outer self-refs
explain (verbose, costs off)
with recursive x(a) as
  ((values ('a'), ('b'))
   union all
   (with z as not materialized (select * from x)
    select z.a || z1.a as a from z cross join z as z1
    where length(z.a || z1.a) < 5))
select * from x;
                        QUERY PLAN                        
----------------------------------------------------------
 CTE Scan on x
   Output: x.a
   CTE x
     ->  Recursive Union
           ->  Values Scan on "*VALUES*"
                 Output: "*VALUES*".column1
           ->  Nested Loop
                 Output: (z.a || z1.a)
                 Join Filter: (length((z.a || z1.a)) < 5)
                 CTE z
                   ->  WorkTable Scan on x x_1
                         Output: x_1.a
                 ->  CTE Scan on z
                       Output: z.a
                 ->  CTE Scan on z z1
                       Output: z1.a
(16 rows)

with recursive x(a) as
  ((values ('a'), ('b'))
   union all
   (with z as not materialized (select * from x)
    select z.a || z1.a as a from z cross join z as z1
    where length(z.a || z1.a) < 5))
select * from x;
  a   
------
 a
 b
 aa
 ab
 ba
 bb
 aaaa
 aaab
 aaba
 aabb
 abaa
 abab
 abba
 abbb
 baaa
 baab
 baba
 babb
 bbaa
 bbab
 bbba
 bbbb
(22 rows)

explain (verbose, costs off)
with recursive x(a) as
  ((values ('a'), ('b'))
   union all
   (with z as not materialized (select * from x)
    select z.a || z.a as a from z
    where length(z.a || z.a) < 5))
select * from x;
                       QUERY PLAN                       
--------------------------------------------------------
 CTE Scan on x
   Output: x.a
   CTE x
     ->  Recursive Union
           ->  Values Scan on "*VALUES*"
                 Output: "*VALUES*".column1
           ->  WorkTable Scan on x x_1
                 Output: (x_1.a || x_1.a)
                 Filter: (length((x_1.a || x_1.a)) < 5)
(9 rows)

with recursive x(a) as
  ((values ('a'), ('b'))
   union all
   (with z as not materialized (select * from x)
    select z.a || z.a as a from z
    where length(z.a || z.a) < 5))
select * from x;
  a   
------
 a
 b
 aa
 bb
 aaaa
 bbbb
(6 rows)

-- Check handling of outer references
explain (verbose, costs off)
with x as (select * from int4_tbl)
select * from (with y as (select * from x) select * from y) ss;
         QUERY PLAN          
-----------------------------
 Seq Scan on public.int4_tbl
   Output: int4_tbl.f1
(2 rows)

explain (verbose, costs off)
with x as materialized (select * from int4_tbl)
select * from (with y as (select * from x) select * from y) ss;
             QUERY PLAN              
-------------------------------------
 CTE Scan on x
   Output: x.f1
   CTE x
     ->  Seq Scan on public.int4_tbl
           Output: int4_tbl.f1
(5 rows)

-- Ensure that we inline the currect CTE when there are
-- multiple CTEs with the same name
explain (verbose, costs off)
with x as (select 1 as y)
select * from (with x as (select 2 as y) select * from x) ss;
 QUERY PLAN  
-------------
 Result
   Output: 2
(2 rows)

-- Row marks are not pushed into CTEs
explain (verbose, costs off)
with x as (select * from subselect_tbl)
select * from x for update;
                           QUERY PLAN                           
----------------------------------------------------------------
 Seq Scan on public.subselect_tbl
   Output: subselect_tbl.f1, subselect_tbl.f2, subselect_tbl.f3
(2 rows)