summaryrefslogtreecommitdiffstats
path: root/doc/src/sgml/plpgsql.sgml
blob: b18e242fde8eedcf6ea051997cae02ad2900ae26 (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
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
<!-- doc/src/sgml/plpgsql.sgml -->

<chapter id="plpgsql">
  <title><application>PL/pgSQL</application> &mdash; <acronym>SQL</acronym> Procedural Language</title>

 <indexterm zone="plpgsql">
  <primary>PL/pgSQL</primary>
 </indexterm>

 <sect1 id="plpgsql-overview">
  <title>Overview</title>

 <para>
  <application>PL/pgSQL</application> is a loadable procedural
  language for the <productname>PostgreSQL</productname> database
  system.  The design goals of <application>PL/pgSQL</application> were to create
  a loadable procedural language that

    <itemizedlist>
     <listitem>
      <para>
       can be used to create functions, procedures, and triggers,
      </para>
     </listitem>
     <listitem>
      <para>
       adds control structures to the <acronym>SQL</acronym> language,
      </para>
     </listitem>
     <listitem>
      <para>
       can perform complex computations,
      </para>
     </listitem>
     <listitem>
      <para>
       inherits all user-defined types, functions, procedures, and operators,
      </para>
     </listitem>
     <listitem>
      <para>
       can be defined to be trusted by the server,
      </para>
     </listitem>
     <listitem>
      <para>
       is easy to use.
      </para>
     </listitem>
    </itemizedlist>
   </para>

   <para>
    Functions created with <application>PL/pgSQL</application> can be
    used anywhere that built-in functions could be used.
    For example, it is possible to
    create complex conditional computation functions and later use
    them to define operators or use them in index expressions.
   </para>

   <para>
    In <productname>PostgreSQL</productname> 9.0 and later,
    <application>PL/pgSQL</application> is installed by default.
    However it is still a loadable module, so especially security-conscious
    administrators could choose to remove it.
   </para>

  <sect2 id="plpgsql-advantages">
   <title>Advantages of Using <application>PL/pgSQL</application></title>

    <para>
     <acronym>SQL</acronym> is the language <productname>PostgreSQL</productname>
     and most other relational databases use as query language. It's
     portable and easy to learn. But every <acronym>SQL</acronym>
     statement must be executed individually by the database server.
    </para>

    <para>
     That means that your client application must send each query to
     the database server, wait for it to be processed, receive and
     process the results, do some computation, then send further
     queries to the server.  All this incurs interprocess
     communication and will also incur network overhead if your client
     is on a different machine than the database server.
    </para>

    <para>
     With <application>PL/pgSQL</application> you can group a block of
     computation and a series of queries <emphasis>inside</emphasis>
     the database server, thus having the power of a procedural
     language and the ease of use of SQL, but with considerable
     savings of client/server communication overhead.
    </para>
    <itemizedlist>

     <listitem><para> Extra round trips between
     client and server are eliminated </para></listitem>

     <listitem><para> Intermediate results that the client does not
     need do not have to be marshaled or transferred between server
     and client </para></listitem>

     <listitem><para> Multiple rounds of query
     parsing can be avoided </para></listitem>

    </itemizedlist>
    <para> This can result in a considerable performance increase as
    compared to an application that does not use stored functions.
    </para>

    <para>
     Also, with <application>PL/pgSQL</application> you can use all
     the data types, operators and functions of SQL.
    </para>
  </sect2>

  <sect2 id="plpgsql-args-results">
   <title>Supported Argument and Result Data Types</title>

    <para>
     Functions written in <application>PL/pgSQL</application> can accept
     as arguments any scalar or array data type supported by the server,
     and they can return a result of any of these types.  They can also
     accept or return any composite type (row type) specified by name.
     It is also possible to declare a <application>PL/pgSQL</application>
     function as accepting <type>record</type>, which means that any
     composite type will do as input, or
     as returning <type>record</type>, which means that the result
     is a row type whose columns are determined by specification in the
     calling query, as discussed in <xref linkend="queries-tablefunctions"/>.
    </para>

    <para>
     <application>PL/pgSQL</application> functions can be declared to accept a variable
     number of arguments by using the <literal>VARIADIC</literal> marker.  This
     works exactly the same way as for SQL functions, as discussed in
     <xref linkend="xfunc-sql-variadic-functions"/>.
    </para>

    <para>
     <application>PL/pgSQL</application> functions can also be declared to
     accept and return the polymorphic types described in
     <xref linkend="extend-types-polymorphic"/>, thus allowing the actual data
     types handled by the function to vary from call to call.
     Examples appear in <xref linkend="plpgsql-declaration-parameters"/>.
    </para>

    <para>
     <application>PL/pgSQL</application> functions can also be declared to return
     a <quote>set</quote> (or table) of any data type that can be returned as
     a single instance.  Such a function generates its output by executing
     <command>RETURN NEXT</command> for each desired element of the result
     set, or by using <command>RETURN QUERY</command> to output the result of
     evaluating a query.
    </para>

    <para>
     Finally, a <application>PL/pgSQL</application> function can be declared to return
     <type>void</type> if it has no useful return value.  (Alternatively, it
     could be written as a procedure in that case.)
    </para>

    <para>
     <application>PL/pgSQL</application> functions can also be declared with output
     parameters in place of an explicit specification of the return type.
     This does not add any fundamental capability to the language, but
     it is often convenient, especially for returning multiple values.
     The <literal>RETURNS TABLE</literal> notation can also be used in place
     of <literal>RETURNS SETOF</literal>.
    </para>

    <para>
     Specific examples appear in
     <xref linkend="plpgsql-declaration-parameters"/> and
     <xref linkend="plpgsql-statements-returning"/>.
    </para>
  </sect2>
 </sect1>

 <sect1 id="plpgsql-structure">
  <title>Structure of <application>PL/pgSQL</application></title>

  <para>
   Functions written in <application>PL/pgSQL</application> are defined
   to the server by executing <xref linkend="sql-createfunction"/> commands.
   Such a command would normally look like, say,
<programlisting>
CREATE FUNCTION somefunc(integer, text) RETURNS integer
AS '<replaceable>function body text</replaceable>'
LANGUAGE plpgsql;
</programlisting>
   The function body is simply a string literal so far as <command>CREATE
   FUNCTION</command> is concerned.  It is often helpful to use dollar quoting
   (see <xref linkend="sql-syntax-dollar-quoting"/>) to write the function
   body, rather than the normal single quote syntax.  Without dollar quoting,
   any single quotes or backslashes in the function body must be escaped by
   doubling them.  Almost all the examples in this chapter use dollar-quoted
   literals for their function bodies.
  </para>

  <para>
   <application>PL/pgSQL</application> is a block-structured language.
   The complete text of a function body must be a
   <firstterm>block</firstterm>. A block is defined as:

<synopsis>
<optional> &lt;&lt;<replaceable>label</replaceable>&gt;&gt; </optional>
<optional> DECLARE
    <replaceable>declarations</replaceable> </optional>
BEGIN
    <replaceable>statements</replaceable>
END <optional> <replaceable>label</replaceable> </optional>;
</synopsis>
    </para>

    <para>
     Each declaration and each statement within a block is terminated
     by a semicolon.  A block that appears within another block must
     have a semicolon after <literal>END</literal>, as shown above;
     however the final <literal>END</literal> that
     concludes a function body does not require a semicolon.
    </para>

    <tip>
     <para>
      A common mistake is to write a semicolon immediately after
      <literal>BEGIN</literal>.  This is incorrect and will result in a syntax error.
     </para>
    </tip>

    <para>
     A <replaceable>label</replaceable> is only needed if you want to
     identify the block for use
     in an <literal>EXIT</literal> statement, or to qualify the names of the
     variables declared in the block.  If a label is given after
     <literal>END</literal>, it must match the label at the block's beginning.
    </para>

    <para>
     All key words are case-insensitive.
     Identifiers are implicitly converted to lower case
     unless double-quoted, just as they are in ordinary SQL commands.
    </para>

    <para>
     Comments work the same way in <application>PL/pgSQL</application> code as in
     ordinary SQL.  A double dash (<literal>--</literal>) starts a comment
     that extends to the end of the line. A <literal>/*</literal> starts a
     block comment that extends to the matching occurrence of
     <literal>*/</literal>.  Block comments nest.
    </para>

    <para>
     Any statement in the statement section of a block
     can be a <firstterm>subblock</firstterm>.  Subblocks can be used for
     logical grouping or to localize variables to a small group
     of statements.  Variables declared in a subblock mask any
     similarly-named variables of outer blocks for the duration
     of the subblock; but you can access the outer variables anyway
     if you qualify their names with their block's label. For example:
<programlisting>
CREATE FUNCTION somefunc() RETURNS integer AS $$
&lt;&lt; outerblock &gt;&gt;
DECLARE
    quantity integer := 30;
BEGIN
    RAISE NOTICE 'Quantity here is %', quantity;  -- Prints 30
    quantity := 50;
    --
    -- Create a subblock
    --
    DECLARE
        quantity integer := 80;
    BEGIN
        RAISE NOTICE 'Quantity here is %', quantity;  -- Prints 80
        RAISE NOTICE 'Outer quantity here is %', outerblock.quantity;  -- Prints 50
    END;

    RAISE NOTICE 'Quantity here is %', quantity;  -- Prints 50

    RETURN quantity;
END;
$$ LANGUAGE plpgsql;
</programlisting>
    </para>

    <note>
     <para>
      There is actually a hidden <quote>outer block</quote> surrounding the body
      of any <application>PL/pgSQL</application> function.  This block provides the
      declarations of the function's parameters (if any), as well as some
      special variables such as <literal>FOUND</literal> (see
      <xref linkend="plpgsql-statements-diagnostics"/>).  The outer block is
      labeled with the function's name, meaning that parameters and special
      variables can be qualified with the function's name.
     </para>
    </note>

    <para>
     It is important not to confuse the use of
     <command>BEGIN</command>/<command>END</command> for grouping statements in
     <application>PL/pgSQL</application> with the similarly-named SQL commands
     for transaction
     control.  <application>PL/pgSQL</application>'s <command>BEGIN</command>/<command>END</command>
     are only for grouping; they do not start or end a transaction.
     See <xref linkend="plpgsql-transactions"/> for information on managing
     transactions in <application>PL/pgSQL</application>.
     Also, a block containing an <literal>EXCEPTION</literal> clause effectively
     forms a subtransaction that can be rolled back without affecting the
     outer transaction.  For more about that see <xref
     linkend="plpgsql-error-trapping"/>.
    </para>
  </sect1>

  <sect1 id="plpgsql-declarations">
    <title>Declarations</title>

    <para>
     All variables used in a block must be declared in the
     declarations section of the block.
     (The only exceptions are that the loop variable of a <literal>FOR</literal> loop
     iterating over a range of integer values is automatically declared as an
     integer variable, and likewise the loop variable of a <literal>FOR</literal> loop
     iterating over a cursor's result is automatically declared as a
     record variable.)
    </para>

    <para>
     <application>PL/pgSQL</application> variables can have any SQL data type, such as
     <type>integer</type>, <type>varchar</type>, and
     <type>char</type>.
    </para>

    <para>
     Here are some examples of variable declarations:
<programlisting>
user_id integer;
quantity numeric(5);
url varchar;
myrow tablename%ROWTYPE;
myfield tablename.columnname%TYPE;
arow RECORD;
</programlisting>
    </para>

    <para>
     The general syntax of a variable declaration is:
<synopsis>
<replaceable>name</replaceable> <optional> CONSTANT </optional> <replaceable>type</replaceable> <optional> COLLATE <replaceable>collation_name</replaceable> </optional> <optional> NOT NULL </optional> <optional> { DEFAULT | := | = } <replaceable>expression</replaceable> </optional>;
</synopsis>
      The <literal>DEFAULT</literal> clause, if given, specifies the initial value assigned
      to the variable when the block is entered.  If the <literal>DEFAULT</literal> clause
      is not given then the variable is initialized to the
      <acronym>SQL</acronym> null value.
      The <literal>CONSTANT</literal> option prevents the variable from being
      assigned to after initialization, so that its value will remain constant
      for the duration of the block.
      The <literal>COLLATE</literal> option specifies a collation to use for the
      variable (see <xref linkend="plpgsql-declaration-collation"/>).
      If <literal>NOT NULL</literal>
      is specified, an assignment of a null value results in a run-time
      error. All variables declared as <literal>NOT NULL</literal>
      must have a nonnull default value specified.
      Equal (<literal>=</literal>) can be used instead of PL/SQL-compliant
      <literal>:=</literal>.
     </para>

     <para>
      A variable's default value is evaluated and assigned to the variable
      each time the block is entered (not just once per function call).
      So, for example, assigning <literal>now()</literal> to a variable of type
      <type>timestamp</type> causes the variable to have the
      time of the current function call, not the time when the function was
      precompiled.
     </para>

     <para>
      Examples:
<programlisting>
quantity integer DEFAULT 32;
url varchar := 'http://mysite.com';
transaction_time CONSTANT timestamp with time zone := now();
</programlisting>
     </para>

     <para>
      Once declared, a variable's value can be used in later initialization
      expressions in the same block, for example:
<programlisting>
DECLARE
  x integer := 1;
  y integer := x + 1;
</programlisting>
     </para>

    <sect2 id="plpgsql-declaration-parameters">
     <title>Declaring Function Parameters</title>

     <para>
      Parameters passed to functions are named with the identifiers
      <literal>$1</literal>, <literal>$2</literal>,
      etc.  Optionally, aliases can be declared for
      <literal>$<replaceable>n</replaceable></literal>
      parameter names for increased readability.  Either the alias or the
      numeric identifier can then be used to refer to the parameter value.
     </para>

     <para>
      There are two ways to create an alias.  The preferred way is to give a
      name to the parameter in the <command>CREATE FUNCTION</command> command,
      for example:
<programlisting>
CREATE FUNCTION sales_tax(subtotal real) RETURNS real AS $$
BEGIN
    RETURN subtotal * 0.06;
END;
$$ LANGUAGE plpgsql;
</programlisting>
      The other way is to explicitly declare an alias, using the
      declaration syntax

<synopsis>
<replaceable>name</replaceable> ALIAS FOR $<replaceable>n</replaceable>;
</synopsis>

      The same example in this style looks like:
<programlisting>
CREATE FUNCTION sales_tax(real) RETURNS real AS $$
DECLARE
    subtotal ALIAS FOR $1;
BEGIN
    RETURN subtotal * 0.06;
END;
$$ LANGUAGE plpgsql;
</programlisting>
     </para>

    <note>
     <para>
      These two examples are not perfectly equivalent.  In the first case,
      <literal>subtotal</literal> could be referenced as
      <literal>sales_tax.subtotal</literal>, but in the second case it could not.
      (Had we attached a label to the inner block, <literal>subtotal</literal> could
      be qualified with that label, instead.)
     </para>
    </note>

     <para>
      Some more examples:
<programlisting>
CREATE FUNCTION instr(varchar, integer) RETURNS integer AS $$
DECLARE
    v_string ALIAS FOR $1;
    index ALIAS FOR $2;
BEGIN
    -- some computations using v_string and index here
END;
$$ LANGUAGE plpgsql;


CREATE FUNCTION concat_selected_fields(in_t sometablename) RETURNS text AS $$
BEGIN
    RETURN in_t.f1 || in_t.f3 || in_t.f5 || in_t.f7;
END;
$$ LANGUAGE plpgsql;
</programlisting>
     </para>

     <para>
      When a <application>PL/pgSQL</application> function is declared
      with output parameters, the output parameters are given
      <literal>$<replaceable>n</replaceable></literal> names and optional
      aliases in just the same way as the normal input parameters.  An
      output parameter is effectively a variable that starts out NULL;
      it should be assigned to during the execution of the function.
      The final value of the parameter is what is returned.  For instance,
      the sales-tax example could also be done this way:

<programlisting>
CREATE FUNCTION sales_tax(subtotal real, OUT tax real) AS $$
BEGIN
    tax := subtotal * 0.06;
END;
$$ LANGUAGE plpgsql;
</programlisting>

      Notice that we omitted <literal>RETURNS real</literal> &mdash; we could have
      included it, but it would be redundant.
     </para>

     <para>
      To call a function with <literal>OUT</literal> parameters, omit the
      output parameter(s) in the function call:
<programlisting>
SELECT sales_tax(100.00);
</programlisting>
     </para>

     <para>
      Output parameters are most useful when returning multiple values.
      A trivial example is:

<programlisting>
CREATE FUNCTION sum_n_product(x int, y int, OUT sum int, OUT prod int) AS $$
BEGIN
    sum := x + y;
    prod := x * y;
END;
$$ LANGUAGE plpgsql;

SELECT * FROM sum_n_product(2, 4);
 sum | prod
-----+------
   6 |    8
</programlisting>

      As discussed in <xref linkend="xfunc-output-parameters"/>, this
      effectively creates an anonymous record type for the function's
      results.  If a <literal>RETURNS</literal> clause is given, it must say
      <literal>RETURNS record</literal>.
     </para>

     <para>
      This also works with procedures, for example:

<programlisting>
CREATE PROCEDURE sum_n_product(x int, y int, OUT sum int, OUT prod int) AS $$
BEGIN
    sum := x + y;
    prod := x * y;
END;
$$ LANGUAGE plpgsql;
</programlisting>

      In a call to a procedure, all the parameters must be specified.  For
      output parameters, <literal>NULL</literal> may be specified when
      calling the procedure from plain SQL:
<programlisting>
CALL sum_n_product(2, 4, NULL, NULL);
 sum | prod
-----+------
   6 |    8
</programlisting>

      However, when calling a procedure
      from <application>PL/pgSQL</application>, you should instead write a
      variable for any output parameter; the variable will receive the result
      of the call.  See <xref linkend="plpgsql-statements-calling-procedure"/>
      for details.
     </para>

     <para>
      Another way to declare a <application>PL/pgSQL</application> function
      is with <literal>RETURNS TABLE</literal>, for example:

<programlisting>
CREATE FUNCTION extended_sales(p_itemno int)
RETURNS TABLE(quantity int, total numeric) AS $$
BEGIN
    RETURN QUERY SELECT s.quantity, s.quantity * s.price FROM sales AS s
                 WHERE s.itemno = p_itemno;
END;
$$ LANGUAGE plpgsql;
</programlisting>

      This is exactly equivalent to declaring one or more <literal>OUT</literal>
      parameters and specifying <literal>RETURNS SETOF
      <replaceable>sometype</replaceable></literal>.
     </para>

     <para>
      When the return type of a <application>PL/pgSQL</application> function
      is declared as a polymorphic type (see
      <xref linkend="extend-types-polymorphic"/>), a special
      parameter <literal>$0</literal> is created.  Its data type is the actual
      return type of the function, as deduced from the actual input types.
      This allows the function to access its actual return type
      as shown in <xref linkend="plpgsql-declaration-type"/>.
      <literal>$0</literal> is initialized to null and can be modified by
      the function, so it can be used to hold the return value if desired,
      though that is not required.  <literal>$0</literal> can also be
      given an alias.  For example, this function works on any data type
      that has a <literal>+</literal> operator:

<programlisting>
CREATE FUNCTION add_three_values(v1 anyelement, v2 anyelement, v3 anyelement)
RETURNS anyelement AS $$
DECLARE
    result ALIAS FOR $0;
BEGIN
    result := v1 + v2 + v3;
    RETURN result;
END;
$$ LANGUAGE plpgsql;
</programlisting>
     </para>

     <para>
      The same effect can be obtained by declaring one or more output parameters as
      polymorphic types.  In this case the
      special <literal>$0</literal> parameter is not used; the output
      parameters themselves serve the same purpose.  For example:

<programlisting>
CREATE FUNCTION add_three_values(v1 anyelement, v2 anyelement, v3 anyelement,
                                 OUT sum anyelement)
AS $$
BEGIN
    sum := v1 + v2 + v3;
END;
$$ LANGUAGE plpgsql;
</programlisting>
     </para>

     <para>
      In practice it might be more useful to declare a polymorphic function
      using the <type>anycompatible</type> family of types, so that automatic
      promotion of the input arguments to a common type will occur.
      For example:

<programlisting>
CREATE FUNCTION add_three_values(v1 anycompatible, v2 anycompatible, v3 anycompatible)
RETURNS anycompatible AS $$
BEGIN
    RETURN v1 + v2 + v3;
END;
$$ LANGUAGE plpgsql;
</programlisting>

      With this example, a call such as

<programlisting>
SELECT add_three_values(1, 2, 4.7);
</programlisting>

      will work, automatically promoting the integer inputs to numeric.
      The function using <type>anyelement</type> would require you to
      cast the three inputs to the same type manually.
     </para>
    </sect2>

  <sect2 id="plpgsql-declaration-alias">
   <title><literal>ALIAS</literal></title>

<synopsis>
<replaceable>newname</replaceable> ALIAS FOR <replaceable>oldname</replaceable>;
</synopsis>

   <para>
    The <literal>ALIAS</literal> syntax is more general than is suggested in the
    previous section: you can declare an alias for any variable, not just
    function parameters.  The main practical use for this is to assign
    a different name for variables with predetermined names, such as
    <varname>NEW</varname> or <varname>OLD</varname> within
    a trigger function.
   </para>

   <para>
    Examples:
<programlisting>
DECLARE
  prior ALIAS FOR old;
  updated ALIAS FOR new;
</programlisting>
   </para>

   <para>
    Since <literal>ALIAS</literal> creates two different ways to name the same
    object, unrestricted use can be confusing.  It's best to use it only
    for the purpose of overriding predetermined names.
   </para>
   </sect2>

  <sect2 id="plpgsql-declaration-type">
   <title>Copying Types</title>

<synopsis>
<replaceable>variable</replaceable>%TYPE
</synopsis>

   <para>
    <literal>%TYPE</literal> provides the data type of a variable or
    table column. You can use this to declare variables that will hold
    database values. For example, let's say you have a column named
    <literal>user_id</literal> in your <literal>users</literal>
    table. To declare a variable with the same data type as
    <literal>users.user_id</literal> you write:
<programlisting>
user_id users.user_id%TYPE;
</programlisting>
   </para>

   <para>
    By using <literal>%TYPE</literal> you don't need to know the data
    type of the structure you are referencing, and most importantly,
    if the data type of the referenced item changes in the future (for
    instance: you change the type of <literal>user_id</literal>
    from <type>integer</type> to <type>real</type>), you might not need
    to change your function definition.
   </para>

   <para>
    <literal>%TYPE</literal> is particularly valuable in polymorphic
    functions, since the data types needed for internal variables can
    change from one call to the next.  Appropriate variables can be
    created by applying <literal>%TYPE</literal> to the function's
    arguments or result placeholders.
   </para>

  </sect2>

    <sect2 id="plpgsql-declaration-rowtypes">
     <title>Row Types</title>

<synopsis>
<replaceable>name</replaceable> <replaceable>table_name</replaceable><literal>%ROWTYPE</literal>;
<replaceable>name</replaceable> <replaceable>composite_type_name</replaceable>;
</synopsis>

   <para>
    A variable of a composite type is called a <firstterm>row</firstterm>
    variable (or <firstterm>row-type</firstterm> variable).  Such a variable
    can hold a whole row of a <command>SELECT</command> or <command>FOR</command>
    query result, so long as that query's column set matches the
    declared type of the variable.
    The individual fields of the row value
    are accessed using the usual dot notation, for example
    <literal>rowvar.field</literal>.
   </para>

   <para>
    A row variable can be declared to have the same type as the rows of
    an existing table or view, by using the
    <replaceable>table_name</replaceable><literal>%ROWTYPE</literal>
    notation; or it can be declared by giving a composite type's name.
    (Since every table has an associated composite type of the same name,
    it actually does not matter in <productname>PostgreSQL</productname> whether you
    write <literal>%ROWTYPE</literal> or not.  But the form with
    <literal>%ROWTYPE</literal> is more portable.)
   </para>

   <para>
    Parameters to a function can be
    composite types (complete table rows). In that case, the
    corresponding identifier <literal>$<replaceable>n</replaceable></literal> will be a row variable, and fields can
    be selected from it, for example <literal>$1.user_id</literal>.
   </para>

   <para>
    Here is an example of using composite types.  <structname>table1</structname>
    and <structname>table2</structname> are existing tables having at least the
    mentioned fields:

<programlisting>
CREATE FUNCTION merge_fields(t_row table1) RETURNS text AS $$
DECLARE
    t2_row table2%ROWTYPE;
BEGIN
    SELECT * INTO t2_row FROM table2 WHERE ... ;
    RETURN t_row.f1 || t2_row.f3 || t_row.f5 || t2_row.f7;
END;
$$ LANGUAGE plpgsql;

SELECT merge_fields(t.*) FROM table1 t WHERE ... ;
</programlisting>
   </para>
  </sect2>

  <sect2 id="plpgsql-declaration-records">
   <title>Record Types</title>

<synopsis>
<replaceable>name</replaceable> RECORD;
</synopsis>

   <para>
    Record variables are similar to row-type variables, but they have no
    predefined structure.  They take on the actual row structure of the
    row they are assigned during a <command>SELECT</command> or <command>FOR</command> command.  The substructure
    of a record variable can change each time it is assigned to.
    A consequence of this is that until a record variable is first assigned
    to, it has no substructure, and any attempt to access a
    field in it will draw a run-time error.
   </para>

   <para>
    Note that <literal>RECORD</literal> is not a true data type, only a placeholder.
    One should also realize that when a <application>PL/pgSQL</application>
    function is declared to return type <type>record</type>, this is not quite the
    same concept as a record variable, even though such a function might
    use a record variable to hold its result.  In both cases the actual row
    structure is unknown when the function is written, but for a function
    returning <type>record</type> the actual structure is determined when the
    calling query is parsed, whereas a record variable can change its row
    structure on-the-fly.
   </para>
  </sect2>

  <sect2 id="plpgsql-declaration-collation">
   <title>Collation of <application>PL/pgSQL</application> Variables</title>

   <indexterm>
    <primary>collation</primary>
    <secondary>in PL/pgSQL</secondary>
   </indexterm>

   <para>
    When a <application>PL/pgSQL</application> function has one or more
    parameters of collatable data types, a collation is identified for each
    function call depending on the collations assigned to the actual
    arguments, as described in <xref linkend="collation"/>.  If a collation is
    successfully identified (i.e., there are no conflicts of implicit
    collations among the arguments) then all the collatable parameters are
    treated as having that collation implicitly.  This will affect the
    behavior of collation-sensitive operations within the function.
    For example, consider

<programlisting>
CREATE FUNCTION less_than(a text, b text) RETURNS boolean AS $$
BEGIN
    RETURN a &lt; b;
END;
$$ LANGUAGE plpgsql;

SELECT less_than(text_field_1, text_field_2) FROM table1;
SELECT less_than(text_field_1, text_field_2 COLLATE "C") FROM table1;
</programlisting>

    The first use of <function>less_than</function> will use the common collation
    of <structfield>text_field_1</structfield> and <structfield>text_field_2</structfield> for
    the comparison, while the second use will use <literal>C</literal> collation.
   </para>

   <para>
    Furthermore, the identified collation is also assumed as the collation of
    any local variables that are of collatable types.  Thus this function
    would not work any differently if it were written as

<programlisting>
CREATE FUNCTION less_than(a text, b text) RETURNS boolean AS $$
DECLARE
    local_a text := a;
    local_b text := b;
BEGIN
    RETURN local_a &lt; local_b;
END;
$$ LANGUAGE plpgsql;
</programlisting>
   </para>

   <para>
    If there are no parameters of collatable data types, or no common
    collation can be identified for them, then parameters and local variables
    use the default collation of their data type (which is usually the
    database's default collation, but could be different for variables of
    domain types).
   </para>

   <para>
    A local variable of a collatable data type can have a different collation
    associated with it by including the <literal>COLLATE</literal> option in its
    declaration, for example

<programlisting>
DECLARE
    local_a text COLLATE "en_US";
</programlisting>

    This option overrides the collation that would otherwise be
    given to the variable according to the rules above.
   </para>

   <para>
    Also, of course explicit <literal>COLLATE</literal> clauses can be written inside
    a function if it is desired to force a particular collation to be used in
    a particular operation.  For example,

<programlisting>
CREATE FUNCTION less_than_c(a text, b text) RETURNS boolean AS $$
BEGIN
    RETURN a &lt; b COLLATE "C";
END;
$$ LANGUAGE plpgsql;
</programlisting>

    This overrides the collations associated with the table columns,
    parameters, or local variables used in the expression, just as would
    happen in a plain SQL command.
   </para>
  </sect2>
  </sect1>

  <sect1 id="plpgsql-expressions">
  <title>Expressions</title>

    <para>
     All expressions used in <application>PL/pgSQL</application>
     statements are processed using the server's main
     <acronym>SQL</acronym> executor.  For example, when you write
     a <application>PL/pgSQL</application> statement like
<synopsis>
IF <replaceable>expression</replaceable> THEN ...
</synopsis>
     <application>PL/pgSQL</application> will evaluate the expression by
     feeding a query like
<synopsis>
SELECT <replaceable>expression</replaceable>
</synopsis>
     to the main SQL engine.  While forming the <command>SELECT</command> command,
     any occurrences of <application>PL/pgSQL</application> variable names
     are replaced by query parameters, as discussed in detail in
     <xref linkend="plpgsql-var-subst"/>.
     This allows the query plan for the <command>SELECT</command> to
     be prepared just once and then reused for subsequent
     evaluations with different values of the variables.  Thus, what
     really happens on first use of an expression is essentially a
     <command>PREPARE</command> command.  For example, if we have declared
     two integer variables <literal>x</literal> and <literal>y</literal>, and we write
<programlisting>
IF x &lt; y THEN ...
</programlisting>
     what happens behind the scenes is equivalent to
<programlisting>
PREPARE <replaceable>statement_name</replaceable>(integer, integer) AS SELECT $1 &lt; $2;
</programlisting>
     and then this prepared statement is <command>EXECUTE</command>d for each
     execution of the <command>IF</command> statement, with the current values
     of the <application>PL/pgSQL</application> variables supplied as
     parameter values.  Normally these details are
     not important to a <application>PL/pgSQL</application> user, but
     they are useful to know when trying to diagnose a problem.
     More information appears in <xref linkend="plpgsql-plan-caching"/>.
    </para>

    <para>
     Since an <replaceable>expression</replaceable> is converted to a
     <literal>SELECT</literal> command, it can contain the same clauses
     that an ordinary <literal>SELECT</literal> would, except that it
     cannot include a top-level <literal>UNION</literal>,
     <literal>INTERSECT</literal>, or <literal>EXCEPT</literal> clause.
     Thus for example one could test whether a table is non-empty with
<programlisting>
IF count(*) &gt; 0 FROM my_table THEN ...
</programlisting>
     since the <replaceable>expression</replaceable>
     between <literal>IF</literal> and <literal>THEN</literal> is parsed as
     though it were <literal>SELECT count(*) &gt; 0 FROM my_table</literal>.
     The <literal>SELECT</literal> must produce a single column, and not
     more than one row.  (If it produces no rows, the result is taken as
     NULL.)
    </para>
  </sect1>

  <sect1 id="plpgsql-statements">
  <title>Basic Statements</title>

   <para>
    In this section and the following ones, we describe all the statement
    types that are explicitly understood by
    <application>PL/pgSQL</application>.
    Anything not recognized as one of these statement types is presumed
    to be an SQL command and is sent to the main database engine to execute,
    as described in <xref linkend="plpgsql-statements-general-sql"/>.
   </para>

   <sect2 id="plpgsql-statements-assignment">
    <title>Assignment</title>

    <para>
     An assignment of a value to a <application>PL/pgSQL</application>
     variable is written as:
<synopsis>
<replaceable>variable</replaceable> { := | = } <replaceable>expression</replaceable>;
</synopsis>
     As explained previously, the expression in such a statement is evaluated
     by means of an SQL <command>SELECT</command> command sent to the main
     database engine.  The expression must yield a single value (possibly
     a row value, if the variable is a row or record variable).  The target
     variable can be a simple variable (optionally qualified with a block
     name), a field of a row or record target, or an element or slice of
     an array target.  Equal (<literal>=</literal>) can be
     used instead of PL/SQL-compliant <literal>:=</literal>.
    </para>

    <para>
     If the expression's result data type doesn't match the variable's
     data type, the value will be coerced as though by an assignment cast
     (see <xref linkend="typeconv-query"/>).  If no assignment cast is known
     for the pair of data types involved, the <application>PL/pgSQL</application>
     interpreter will attempt to convert the result value textually, that is
     by applying the result type's output function followed by the variable
     type's input function.  Note that this could result in run-time errors
     generated by the input function, if the string form of the result value
     is not acceptable to the input function.
    </para>

    <para>
     Examples:
<programlisting>
tax := subtotal * 0.06;
my_record.user_id := 20;
my_array[j] := 20;
my_array[1:3] := array[1,2,3];
complex_array[n].realpart = 12.3;
</programlisting>
    </para>
   </sect2>

   <sect2 id="plpgsql-statements-general-sql">
    <title>Executing SQL Commands</title>

    <para>
     In general, any SQL command that does not return rows can be executed
     within a <application>PL/pgSQL</application> function just by writing
     the command.  For example, you could create and fill a table by writing
<programlisting>
CREATE TABLE mytable (id int primary key, data text);
INSERT INTO mytable VALUES (1,'one'), (2,'two');
</programlisting>
    </para>

    <para>
     If the command does return rows (for example <command>SELECT</command>,
     or <command>INSERT</command>/<command>UPDATE</command>/<command>DELETE</command>
     with <literal>RETURNING</literal>), there are two ways to proceed.
     When the command will return at most one row, or you only care about
     the first row of output, write the command as usual but add
     an <literal>INTO</literal> clause to capture the output, as described
     in <xref linkend="plpgsql-statements-sql-onerow"/>.
     To process all of the output rows, write the command as the data
     source for a <command>FOR</command> loop, as described in
     <xref linkend="plpgsql-records-iterating"/>.
    </para>

    <para>
     Usually it is not sufficient just to execute statically-defined SQL
     commands.  Typically you'll want a command to use varying data values,
     or even to vary in more fundamental ways such as by using different
     table names at different times.  Again, there are two ways to proceed
     depending on the situation.
    </para>

    <para>
     <application>PL/pgSQL</application> variable values can be
     automatically inserted into optimizable SQL commands, which
     are <command>SELECT</command>, <command>INSERT</command>,
     <command>UPDATE</command>, <command>DELETE</command>,
     <command>MERGE</command>, and certain
     utility commands that incorporate one of these, such
     as <command>EXPLAIN</command> and <command>CREATE TABLE ... AS
     SELECT</command>.  In these commands,
     any <application>PL/pgSQL</application> variable name appearing
     in the command text is replaced by a query parameter, and then the
     current value of the variable is provided as the parameter value
     at run time.  This is exactly like the processing described earlier
     for expressions; for details see <xref linkend="plpgsql-var-subst"/>.
    </para>

    <para>
     When executing an optimizable SQL command in this way,
     <application>PL/pgSQL</application> may cache and re-use the execution
     plan for the command, as discussed in
     <xref linkend="plpgsql-plan-caching"/>.
    </para>

    <para>
     Non-optimizable SQL commands (also called utility commands) are not
     capable of accepting query parameters.  So automatic substitution
     of <application>PL/pgSQL</application> variables does not work in such
     commands.  To include non-constant text in a utility command executed
     from <application>PL/pgSQL</application>, you must build the utility
     command as a string and then <command>EXECUTE</command> it, as
     discussed in <xref linkend="plpgsql-statements-executing-dyn"/>.
    </para>

    <para>
     <command>EXECUTE</command> must also be used if you want to modify
     the command in some other way than supplying a data value, for example
     by changing a table name.
    </para>

    <para>
     Sometimes it is useful to evaluate an expression or <command>SELECT</command>
     query but discard the result, for example when calling a function
     that has side-effects but no useful result value.  To do
     this in <application>PL/pgSQL</application>, use the
     <command>PERFORM</command> statement:

<synopsis>
PERFORM <replaceable>query</replaceable>;
</synopsis>

     This executes <replaceable>query</replaceable> and discards the
     result.  Write the <replaceable>query</replaceable> the same
     way you would write an SQL <command>SELECT</command> command, but replace the
     initial keyword <command>SELECT</command> with <command>PERFORM</command>.
     For <command>WITH</command> queries, use <command>PERFORM</command> and then
     place the query in parentheses.  (In this case, the query can only
     return one row.)
     <application>PL/pgSQL</application> variables will be
     substituted into the query just as described above,
     and the plan is cached in the same way.  Also, the special variable
     <literal>FOUND</literal> is set to true if the query produced at
     least one row, or false if it produced no rows (see
     <xref linkend="plpgsql-statements-diagnostics"/>).
    </para>

    <note>
     <para>
      One might expect that writing <command>SELECT</command> directly
      would accomplish this result, but at
      present the only accepted way to do it is
      <command>PERFORM</command>.  An SQL command that can return rows,
      such as <command>SELECT</command>, will be rejected as an error
      unless it has an <literal>INTO</literal> clause as discussed in the
      next section.
     </para>
    </note>

    <para>
     An example:
<programlisting>
PERFORM create_mv('cs_session_page_requests_mv', my_query);
</programlisting>
    </para>
   </sect2>

   <sect2 id="plpgsql-statements-sql-onerow">
    <title>Executing a Command with a Single-Row Result</title>

    <indexterm zone="plpgsql-statements-sql-onerow">
     <primary>SELECT INTO</primary>
     <secondary>in PL/pgSQL</secondary>
    </indexterm>

    <indexterm zone="plpgsql-statements-sql-onerow">
     <primary>RETURNING INTO</primary>
     <secondary>in PL/pgSQL</secondary>
    </indexterm>

    <para>
     The result of an SQL command yielding a single row (possibly of multiple
     columns) can be assigned to a record variable, row-type variable, or list
     of scalar variables.  This is done by writing the base SQL command and
     adding an <literal>INTO</literal> clause.  For example,

<synopsis>
SELECT <replaceable>select_expressions</replaceable> INTO <optional>STRICT</optional> <replaceable>target</replaceable> FROM ...;
INSERT ... RETURNING <replaceable>expressions</replaceable> INTO <optional>STRICT</optional> <replaceable>target</replaceable>;
UPDATE ... RETURNING <replaceable>expressions</replaceable> INTO <optional>STRICT</optional> <replaceable>target</replaceable>;
DELETE ... RETURNING <replaceable>expressions</replaceable> INTO <optional>STRICT</optional> <replaceable>target</replaceable>;
</synopsis>

     where <replaceable>target</replaceable> can be a record variable, a row
     variable, or a comma-separated list of simple variables and
     record/row fields.
     <application>PL/pgSQL</application> variables will be
     substituted into the rest of the command (that is, everything but the
     <literal>INTO</literal> clause) just as described above,
     and the plan is cached in the same way.
     This works for <command>SELECT</command>,
     <command>INSERT</command>/<command>UPDATE</command>/<command>DELETE</command> with
     <literal>RETURNING</literal>, and certain utility commands
     that return row sets, such as <command>EXPLAIN</command>.
     Except for the <literal>INTO</literal> clause, the SQL command is the same
     as it would be written outside <application>PL/pgSQL</application>.
    </para>

   <tip>
    <para>
     Note that this interpretation of <command>SELECT</command> with <literal>INTO</literal>
     is quite different from <productname>PostgreSQL</productname>'s regular
     <command>SELECT INTO</command> command, wherein the <literal>INTO</literal>
     target is a newly created table.  If you want to create a table from a
     <command>SELECT</command> result inside a
     <application>PL/pgSQL</application> function, use the syntax
     <command>CREATE TABLE ... AS SELECT</command>.
    </para>
   </tip>

    <para>
     If a row variable or a variable list is used as target,
     the command's result columns
     must exactly match the structure of the target as to number and data
     types, or else a run-time error
     occurs.  When a record variable is the target, it automatically
     configures itself to the row type of the command's result columns.
    </para>

    <para>
     The <literal>INTO</literal> clause can appear almost anywhere in the SQL
     command.  Customarily it is written either just before or just after
     the list of <replaceable>select_expressions</replaceable> in a
     <command>SELECT</command> command, or at the end of the command for other
     command types.  It is recommended that you follow this convention
     in case the <application>PL/pgSQL</application> parser becomes
     stricter in future versions.
    </para>

    <para>
     If <literal>STRICT</literal> is not specified in the <literal>INTO</literal>
     clause, then <replaceable>target</replaceable> will be set to the first
     row returned by the command, or to nulls if the command returned no rows.
     (Note that <quote>the first row</quote> is not
     well-defined unless you've used <literal>ORDER BY</literal>.)  Any result rows
     after the first row are discarded.
     You can check the special <literal>FOUND</literal> variable (see
     <xref linkend="plpgsql-statements-diagnostics"/>) to
     determine whether a row was returned:

<programlisting>
SELECT * INTO myrec FROM emp WHERE empname = myname;
IF NOT FOUND THEN
    RAISE EXCEPTION 'employee % not found', myname;
END IF;
</programlisting>

     If the <literal>STRICT</literal> option is specified, the command must
     return exactly one row or a run-time error will be reported, either
     <literal>NO_DATA_FOUND</literal> (no rows) or <literal>TOO_MANY_ROWS</literal>
     (more than one row). You can use an exception block if you wish
     to catch the error, for example:

<programlisting>
BEGIN
    SELECT * INTO STRICT myrec FROM emp WHERE empname = myname;
    EXCEPTION
        WHEN NO_DATA_FOUND THEN
            RAISE EXCEPTION 'employee % not found', myname;
        WHEN TOO_MANY_ROWS THEN
            RAISE EXCEPTION 'employee % not unique', myname;
END;
</programlisting>
     Successful execution of a command with <literal>STRICT</literal>
     always sets <literal>FOUND</literal> to true.
    </para>

    <para>
     For <command>INSERT</command>/<command>UPDATE</command>/<command>DELETE</command> with
     <literal>RETURNING</literal>, <application>PL/pgSQL</application> reports
     an error for more than one returned row, even when
     <literal>STRICT</literal> is not specified.  This is because there
     is no option such as <literal>ORDER BY</literal> with which to determine
     which affected row should be returned.
    </para>

    <para>
     If <literal>print_strict_params</literal> is enabled for the function,
     then when an error is thrown because the requirements
     of <literal>STRICT</literal> are not met, the <literal>DETAIL</literal> part of
     the error message will include information about the parameters
     passed to the command.
     You can change the <literal>print_strict_params</literal>
     setting for all functions by setting
     <varname>plpgsql.print_strict_params</varname>, though only subsequent
     function compilations will be affected.  You can also enable it
     on a per-function basis by using a compiler option, for example:
<programlisting>
CREATE FUNCTION get_userid(username text) RETURNS int
AS $$
#print_strict_params on
DECLARE
userid int;
BEGIN
    SELECT users.userid INTO STRICT userid
        FROM users WHERE users.username = get_userid.username;
    RETURN userid;
END;
$$ LANGUAGE plpgsql;
</programlisting>
     On failure, this function might produce an error message such as
<programlisting>
ERROR:  query returned no rows
DETAIL:  parameters: $1 = 'nosuchuser'
CONTEXT:  PL/pgSQL function get_userid(text) line 6 at SQL statement
</programlisting>
    </para>

    <note>
     <para>
      The <literal>STRICT</literal> option matches the behavior of
      Oracle PL/SQL's <command>SELECT INTO</command> and related statements.
     </para>
    </note>

   </sect2>

   <sect2 id="plpgsql-statements-executing-dyn">
    <title>Executing Dynamic Commands</title>

    <para>
     Oftentimes you will want to generate dynamic commands inside your
     <application>PL/pgSQL</application> functions, that is, commands
     that will involve different tables or different data types each
     time they are executed.  <application>PL/pgSQL</application>'s
     normal attempts to cache plans for commands (as discussed in
     <xref linkend="plpgsql-plan-caching"/>) will not work in such
     scenarios.  To handle this sort of problem, the
     <command>EXECUTE</command> statement is provided:

<synopsis>
EXECUTE <replaceable class="command">command-string</replaceable> <optional> INTO <optional>STRICT</optional> <replaceable>target</replaceable> </optional> <optional> USING <replaceable>expression</replaceable> <optional>, ... </optional> </optional>;
</synopsis>

     where <replaceable>command-string</replaceable> is an expression
     yielding a string (of type <type>text</type>) containing the
     command to be executed.  The optional <replaceable>target</replaceable>
     is a record variable, a row variable, or a comma-separated list of
     simple variables and record/row fields, into which the results of
     the command will be stored.  The optional <literal>USING</literal> expressions
     supply values to be inserted into the command.
    </para>

    <para>
     No substitution of <application>PL/pgSQL</application> variables is done on the
     computed command string.  Any required variable values must be inserted
     in the command string as it is constructed; or you can use parameters
     as described below.
    </para>

    <para>
     Also, there is no plan caching for commands executed via
     <command>EXECUTE</command>.  Instead, the command is always planned
     each time the statement is run. Thus the command
     string can be dynamically created within the function to perform
     actions on different tables and columns.
    </para>

    <para>
     The <literal>INTO</literal> clause specifies where the results of
     an SQL command returning rows should be assigned. If a row variable
     or variable list is provided, it must exactly match the structure
     of the command's results; if a
     record variable is provided, it will configure itself to match the
     result structure automatically. If multiple rows are returned,
     only the first will be assigned to the <literal>INTO</literal>
     variable(s). If no rows are returned, NULL is assigned to the
     <literal>INTO</literal> variable(s). If no <literal>INTO</literal>
     clause is specified, the command results are discarded.
    </para>

    <para>
     If the <literal>STRICT</literal> option is given, an error is reported
     unless the command produces exactly one row.
    </para>

    <para>
     The command string can use parameter values, which are referenced
     in the command as <literal>$1</literal>, <literal>$2</literal>, etc.
     These symbols refer to values supplied in the <literal>USING</literal>
     clause.  This method is often preferable to inserting data values
     into the command string as text: it avoids run-time overhead of
     converting the values to text and back, and it is much less prone
     to SQL-injection attacks since there is no need for quoting or escaping.
     An example is:
<programlisting>
EXECUTE 'SELECT count(*) FROM mytable WHERE inserted_by = $1 AND inserted &lt;= $2'
   INTO c
   USING checked_user, checked_date;
</programlisting>
    </para>

    <para>
     Note that parameter symbols can only be used for data values
     &mdash; if you want to use dynamically determined table or column
     names, you must insert them into the command string textually.
     For example, if the preceding query needed to be done against a
     dynamically selected table, you could do this:
<programlisting>
EXECUTE 'SELECT count(*) FROM '
    || quote_ident(tabname)
    || ' WHERE inserted_by = $1 AND inserted &lt;= $2'
   INTO c
   USING checked_user, checked_date;
</programlisting>
     A cleaner approach is to use <function>format()</function>'s <literal>%I</literal>
     specification to insert table or column names with automatic quoting:
<programlisting>
EXECUTE format('SELECT count(*) FROM %I '
   'WHERE inserted_by = $1 AND inserted &lt;= $2', tabname)
   INTO c
   USING checked_user, checked_date;
</programlisting>
     (This example relies on the SQL rule that string literals separated by a
     newline are implicitly concatenated.)
    </para>

    <para>
     Another restriction on parameter symbols is that they only work in
     optimizable SQL commands
     (<command>SELECT</command>, <command>INSERT</command>, <command>UPDATE</command>,
     <command>DELETE</command>, <command>MERGE</command>, and certain commands containing one of these).
     In other statement
     types (generically called utility statements), you must insert
     values textually even if they are just data values.
    </para>

    <para>
     An <command>EXECUTE</command> with a simple constant command string and some
     <literal>USING</literal> parameters, as in the first example above, is
     functionally equivalent to just writing the command directly in
     <application>PL/pgSQL</application> and allowing replacement of
     <application>PL/pgSQL</application> variables to happen automatically.
     The important difference is that <command>EXECUTE</command> will re-plan
     the command on each execution, generating a plan that is specific
     to the current parameter values; whereas
     <application>PL/pgSQL</application> may otherwise create a generic plan
     and cache it for re-use.  In situations where the best plan depends
     strongly on the parameter values, it can be helpful to use
     <command>EXECUTE</command> to positively ensure that a generic plan is not
     selected.
    </para>

    <para>
     <command>SELECT INTO</command> is not currently supported within
     <command>EXECUTE</command>; instead, execute a plain <command>SELECT</command>
     command and specify <literal>INTO</literal> as part of the <command>EXECUTE</command>
     itself.
    </para>

   <note>
    <para>
     The <application>PL/pgSQL</application>
     <command>EXECUTE</command> statement is not related to the
     <link linkend="sql-execute"><command>EXECUTE</command></link> SQL
     statement supported by the
     <productname>PostgreSQL</productname> server. The server's
     <command>EXECUTE</command> statement cannot be used directly within
     <application>PL/pgSQL</application> functions (and is not needed).
    </para>
   </note>

   <example id="plpgsql-quote-literal-example">
   <title>Quoting Values in Dynamic Queries</title>

    <indexterm>
     <primary>quote_ident</primary>
     <secondary>use in PL/pgSQL</secondary>
    </indexterm>

    <indexterm>
     <primary>quote_literal</primary>
     <secondary>use in PL/pgSQL</secondary>
    </indexterm>

    <indexterm>
     <primary>quote_nullable</primary>
     <secondary>use in PL/pgSQL</secondary>
    </indexterm>

    <indexterm>
     <primary>format</primary>
     <secondary>use in PL/pgSQL</secondary>
    </indexterm>

    <para>
     When working with dynamic commands you will often have to handle escaping
     of single quotes.  The recommended method for quoting fixed text in your
     function body is dollar quoting.  (If you have legacy code that does
     not use dollar quoting, please refer to the
     overview in <xref linkend="plpgsql-quote-tips"/>, which can save you
     some effort when translating said code to a more reasonable scheme.)
    </para>

    <para>
     Dynamic values require careful handling since they might contain
     quote characters.
     An example using <function>format()</function> (this assumes that you are
     dollar quoting the function body so quote marks need not be doubled):
<programlisting>
EXECUTE format('UPDATE tbl SET %I = $1 '
   'WHERE key = $2', colname) USING newvalue, keyvalue;
</programlisting>
     It is also possible to call the quoting functions directly:
<programlisting>
EXECUTE 'UPDATE tbl SET '
        || quote_ident(colname)
        || ' = '
        || quote_literal(newvalue)
        || ' WHERE key = '
        || quote_literal(keyvalue);
</programlisting>
    </para>

    <para>
     This example demonstrates the use of the
     <function>quote_ident</function> and
     <function>quote_literal</function> functions (see <xref
     linkend="functions-string"/>).  For safety, expressions containing column
     or table identifiers should be passed through
     <function>quote_ident</function> before insertion in a dynamic query.
     Expressions containing values that should be literal strings in the
     constructed command should be passed through <function>quote_literal</function>.
     These functions take the appropriate steps to return the input text
     enclosed in double or single quotes respectively, with any embedded
     special characters properly escaped.
    </para>

    <para>
     Because <function>quote_literal</function> is labeled
     <literal>STRICT</literal>, it will always return null when called with a
     null argument.  In the above example, if <literal>newvalue</literal> or
     <literal>keyvalue</literal> were null, the entire dynamic query string would
     become null, leading to an error from <command>EXECUTE</command>.
     You can avoid this problem by using the <function>quote_nullable</function>
     function, which works the same as <function>quote_literal</function> except that
     when called with a null argument it returns the string <literal>NULL</literal>.
     For example,
<programlisting>
EXECUTE 'UPDATE tbl SET '
        || quote_ident(colname)
        || ' = '
        || quote_nullable(newvalue)
        || ' WHERE key = '
        || quote_nullable(keyvalue);
</programlisting>
     If you are dealing with values that might be null, you should usually
     use <function>quote_nullable</function> in place of <function>quote_literal</function>.
    </para>

    <para>
     As always, care must be taken to ensure that null values in a query do
     not deliver unintended results.  For example the <literal>WHERE</literal> clause
<programlisting>
'WHERE key = ' || quote_nullable(keyvalue)
</programlisting>
     will never succeed if <literal>keyvalue</literal> is null, because the
     result of using the equality operator <literal>=</literal> with a null operand
     is always null.  If you wish null to work like an ordinary key value,
     you would need to rewrite the above as
<programlisting>
'WHERE key IS NOT DISTINCT FROM ' || quote_nullable(keyvalue)
</programlisting>
     (At present, <literal>IS NOT DISTINCT FROM</literal> is handled much less
     efficiently than <literal>=</literal>, so don't do this unless you must.
     See <xref linkend="functions-comparison"/> for
     more information on nulls and <literal>IS DISTINCT</literal>.)
    </para>

    <para>
     Note that dollar quoting is only useful for quoting fixed text.
     It would be a very bad idea to try to write this example as:
<programlisting>
EXECUTE 'UPDATE tbl SET '
        || quote_ident(colname)
        || ' = $$'
        || newvalue
        || '$$ WHERE key = '
        || quote_literal(keyvalue);
</programlisting>
     because it would break if the contents of <literal>newvalue</literal>
     happened to contain <literal>$$</literal>.  The same objection would
     apply to any other dollar-quoting delimiter you might pick.
     So, to safely quote text that is not known in advance, you
     <emphasis>must</emphasis> use <function>quote_literal</function>,
     <function>quote_nullable</function>, or <function>quote_ident</function>, as appropriate.
    </para>

    <para>
     Dynamic SQL statements can also be safely constructed using the
     <function>format</function> function (see <xref
     linkend="functions-string-format"/>). For example:
<programlisting>
EXECUTE format('UPDATE tbl SET %I = %L '
   'WHERE key = %L', colname, newvalue, keyvalue);
</programlisting>
     <literal>%I</literal> is equivalent to <function>quote_ident</function>, and
     <literal>%L</literal> is equivalent to <function>quote_nullable</function>.
     The <function>format</function> function can be used in conjunction with
     the <literal>USING</literal> clause:
<programlisting>
EXECUTE format('UPDATE tbl SET %I = $1 WHERE key = $2', colname)
   USING newvalue, keyvalue;
</programlisting>
     This form is better because the variables are handled in their native
     data type format, rather than unconditionally converting them to
     text and quoting them via <literal>%L</literal>.  It is also more efficient.
    </para>
   </example>

    <para>
     A much larger example of a dynamic command and
     <command>EXECUTE</command> can be seen in <xref
     linkend="plpgsql-porting-ex2"/>, which builds and executes a
     <command>CREATE FUNCTION</command> command to define a new function.
    </para>
   </sect2>

   <sect2 id="plpgsql-statements-diagnostics">
    <title>Obtaining the Result Status</title>

    <para>
     There are several ways to determine the effect of a command. The
     first method is to use the <command>GET DIAGNOSTICS</command>
     command, which has the form:

<synopsis>
GET <optional> CURRENT </optional> DIAGNOSTICS <replaceable>variable</replaceable> { = | := } <replaceable>item</replaceable> <optional> , ... </optional>;
</synopsis>

     This command allows retrieval of system status indicators.
     <literal>CURRENT</literal> is a noise word (but see also <command>GET STACKED
     DIAGNOSTICS</command> in <xref linkend="plpgsql-exception-diagnostics"/>).
     Each <replaceable>item</replaceable> is a key word identifying a status
     value to be assigned to the specified <replaceable>variable</replaceable>
     (which should be of the right data type to receive it).  The currently
     available status items are shown
     in <xref linkend="plpgsql-current-diagnostics-values"/>.  Colon-equal
     (<literal>:=</literal>) can be used instead of the SQL-standard <literal>=</literal>
     token.  An example:
<programlisting>
GET DIAGNOSTICS integer_var = ROW_COUNT;
</programlisting>
    </para>

     <table id="plpgsql-current-diagnostics-values">
      <title>Available Diagnostics Items</title>
      <tgroup cols="3">
       <colspec colname="col1" colwidth="1*"/>
       <colspec colname="col2" colwidth="1*"/>
       <colspec colname="col3" colwidth="2*"/>
       <thead>
        <row>
         <entry>Name</entry>
         <entry>Type</entry>
         <entry>Description</entry>
        </row>
       </thead>
       <tbody>
        <row>
         <entry><varname>ROW_COUNT</varname></entry>
         <entry><type>bigint</type></entry>
         <entry>the number of rows processed by the most
          recent <acronym>SQL</acronym> command</entry>
        </row>
        <row>
         <entry><literal>PG_CONTEXT</literal></entry>
         <entry><type>text</type></entry>
         <entry>line(s) of text describing the current call stack
          (see <xref linkend="plpgsql-call-stack"/>)</entry>
        </row>
       </tbody>
      </tgroup>
     </table>

    <para>
     The second method to determine the effects of a command is to check the
     special variable named <literal>FOUND</literal>, which is of
     type <type>boolean</type>.  <literal>FOUND</literal> starts out
     false within each <application>PL/pgSQL</application> function call.
     It is set by each of the following types of statements:

         <itemizedlist>
          <listitem>
           <para>
            A <command>SELECT INTO</command> statement sets
            <literal>FOUND</literal> true if a row is assigned, false if no
            row is returned.
           </para>
          </listitem>
          <listitem>
           <para>
            A <command>PERFORM</command> statement sets <literal>FOUND</literal>
            true if it produces (and discards) one or more rows, false if
            no row is produced.
           </para>
          </listitem>
          <listitem>
           <para>
            <command>UPDATE</command>, <command>INSERT</command>, <command>DELETE</command>,
            and <command>MERGE</command>
            statements set <literal>FOUND</literal> true if at least one
            row is affected, false if no row is affected.
           </para>
          </listitem>
          <listitem>
           <para>
            A <command>FETCH</command> statement sets <literal>FOUND</literal>
            true if it returns a row, false if no row is returned.
           </para>
          </listitem>
          <listitem>
           <para>
            A <command>MOVE</command> statement sets <literal>FOUND</literal>
            true if it successfully repositions the cursor, false otherwise.
           </para>
          </listitem>
          <listitem>
           <para>
            A <command>FOR</command> or <command>FOREACH</command> statement sets
            <literal>FOUND</literal> true
            if it iterates one or more times, else false.
            <literal>FOUND</literal> is set this way when the
            loop exits; inside the execution of the loop,
            <literal>FOUND</literal> is not modified by the
            loop statement, although it might be changed by the
            execution of other statements within the loop body.
           </para>
          </listitem>
          <listitem>
           <para>
            <command>RETURN QUERY</command> and <command>RETURN QUERY
            EXECUTE</command> statements set <literal>FOUND</literal>
            true if the query returns at least one row, false if no row
            is returned.
           </para>
          </listitem>
         </itemizedlist>

     Other <application>PL/pgSQL</application> statements do not change
     the state of <literal>FOUND</literal>.
     Note in particular that <command>EXECUTE</command>
     changes the output of <command>GET DIAGNOSTICS</command>, but
     does not change <literal>FOUND</literal>.
    </para>

    <para>
     <literal>FOUND</literal> is a local variable within each
     <application>PL/pgSQL</application> function; any changes to it
     affect only the current function.
    </para>

   </sect2>

   <sect2 id="plpgsql-statements-null">
    <title>Doing Nothing At All</title>

    <para>
     Sometimes a placeholder statement that does nothing is useful.
     For example, it can indicate that one arm of an if/then/else
     chain is deliberately empty.  For this purpose, use the
     <command>NULL</command> statement:

<synopsis>
NULL;
</synopsis>
    </para>

    <para>
     For example, the following two fragments of code are equivalent:
<programlisting>
BEGIN
    y := x / 0;
EXCEPTION
    WHEN division_by_zero THEN
        NULL;  -- ignore the error
END;
</programlisting>

<programlisting>
BEGIN
    y := x / 0;
EXCEPTION
    WHEN division_by_zero THEN  -- ignore the error
END;
</programlisting>
     Which is preferable is a matter of taste.
    </para>

    <note>
     <para>
      In Oracle's PL/SQL, empty statement lists are not allowed, and so
      <command>NULL</command> statements are <emphasis>required</emphasis> for situations
      such as this.  <application>PL/pgSQL</application> allows you to
      just write nothing, instead.
     </para>
    </note>

   </sect2>
  </sect1>

  <sect1 id="plpgsql-control-structures">
   <title>Control Structures</title>

   <para>
    Control structures are probably the most useful (and
    important) part of <application>PL/pgSQL</application>. With
    <application>PL/pgSQL</application>'s control structures,
    you can manipulate <productname>PostgreSQL</productname> data in a very
    flexible and powerful way.
   </para>

   <sect2 id="plpgsql-statements-returning">
    <title>Returning from a Function</title>

    <para>
     There are two commands available that allow you to return data
     from a function: <command>RETURN</command> and <command>RETURN
     NEXT</command>.
    </para>

    <sect3>
     <title><command>RETURN</command></title>

<synopsis>
RETURN <replaceable>expression</replaceable>;
</synopsis>

     <para>
      <command>RETURN</command> with an expression terminates the
      function and returns the value of
      <replaceable>expression</replaceable> to the caller.  This form
      is used for <application>PL/pgSQL</application> functions that do
      not return a set.
     </para>

     <para>
      In a function that returns a scalar type, the expression's result will
      automatically be cast into the function's return type as described for
      assignments.  But to return a composite (row) value, you must write an
      expression delivering exactly the requested column set.  This may
      require use of explicit casting.
     </para>

     <para>
      If you declared the function with output parameters, write just
      <command>RETURN</command> with no expression.  The current values
      of the output parameter variables will be returned.
     </para>

     <para>
      If you declared the function to return <type>void</type>, a
      <command>RETURN</command> statement can be used to exit the function
      early; but do not write an expression following
      <command>RETURN</command>.
     </para>

     <para>
      The return value of a function cannot be left undefined. If
      control reaches the end of the top-level block of the function
      without hitting a <command>RETURN</command> statement, a run-time
      error will occur.  This restriction does not apply to functions
      with output parameters and functions returning <type>void</type>,
      however.  In those cases a <command>RETURN</command> statement is
      automatically executed if the top-level block finishes.
     </para>

     <para>
      Some examples:

<programlisting>
-- functions returning a scalar type
RETURN 1 + 2;
RETURN scalar_var;

-- functions returning a composite type
RETURN composite_type_var;
RETURN (1, 2, 'three'::text);  -- must cast columns to correct types
</programlisting>
     </para>
    </sect3>

    <sect3>
     <title><command>RETURN NEXT</command> and <command>RETURN QUERY</command></title>
    <indexterm>
     <primary>RETURN NEXT</primary>
     <secondary>in PL/pgSQL</secondary>
    </indexterm>
    <indexterm>
     <primary>RETURN QUERY</primary>
     <secondary>in PL/pgSQL</secondary>
    </indexterm>

<synopsis>
RETURN NEXT <replaceable>expression</replaceable>;
RETURN QUERY <replaceable>query</replaceable>;
RETURN QUERY EXECUTE <replaceable class="command">command-string</replaceable> <optional> USING <replaceable>expression</replaceable> <optional>, ... </optional> </optional>;
</synopsis>

     <para>
      When a <application>PL/pgSQL</application> function is declared to return
      <literal>SETOF <replaceable>sometype</replaceable></literal>, the procedure
      to follow is slightly different.  In that case, the individual
      items to return are specified by a sequence of <command>RETURN
      NEXT</command> or <command>RETURN QUERY</command> commands, and
      then a final <command>RETURN</command> command with no argument
      is used to indicate that the function has finished executing.
      <command>RETURN NEXT</command> can be used with both scalar and
      composite data types; with a composite result type, an entire
      <quote>table</quote> of results will be returned.
      <command>RETURN QUERY</command> appends the results of executing
      a query to the function's result set. <command>RETURN
      NEXT</command> and <command>RETURN QUERY</command> can be freely
      intermixed in a single set-returning function, in which case
      their results will be concatenated.
     </para>

     <para>
      <command>RETURN NEXT</command> and <command>RETURN
      QUERY</command> do not actually return from the function &mdash;
      they simply append zero or more rows to the function's result
      set.  Execution then continues with the next statement in the
      <application>PL/pgSQL</application> function.  As successive
      <command>RETURN NEXT</command> or <command>RETURN
      QUERY</command> commands are executed, the result set is built
      up.  A final <command>RETURN</command>, which should have no
      argument, causes control to exit the function (or you can just
      let control reach the end of the function).
     </para>

     <para>
      <command>RETURN QUERY</command> has a variant
      <command>RETURN QUERY EXECUTE</command>, which specifies the
      query to be executed dynamically.  Parameter expressions can
      be inserted into the computed query string via <literal>USING</literal>,
      in just the same way as in the <command>EXECUTE</command> command.
     </para>

     <para>
      If you declared the function with output parameters, write just
      <command>RETURN NEXT</command> with no expression.  On each
      execution, the current values of the output parameter
      variable(s) will be saved for eventual return as a row of the
      result.  Note that you must declare the function as returning
      <literal>SETOF record</literal> when there are multiple output
      parameters, or <literal>SETOF <replaceable>sometype</replaceable></literal>
      when there is just one output parameter of type
      <replaceable>sometype</replaceable>, in order to create a set-returning
      function with output parameters.
     </para>

     <para>
      Here is an example of a function using <command>RETURN
      NEXT</command>:

<programlisting>
CREATE TABLE foo (fooid INT, foosubid INT, fooname TEXT);
INSERT INTO foo VALUES (1, 2, 'three');
INSERT INTO foo VALUES (4, 5, 'six');

CREATE OR REPLACE FUNCTION get_all_foo() RETURNS SETOF foo AS
$BODY$
DECLARE
    r foo%rowtype;
BEGIN
    FOR r IN
        SELECT * FROM foo WHERE fooid &gt; 0
    LOOP
        -- can do some processing here
        RETURN NEXT r; -- return current row of SELECT
    END LOOP;
    RETURN;
END;
$BODY$
LANGUAGE plpgsql;

SELECT * FROM get_all_foo();
</programlisting>
     </para>

     <para>
      Here is an example of a function using <command>RETURN
      QUERY</command>:

<programlisting>
CREATE FUNCTION get_available_flightid(date) RETURNS SETOF integer AS
$BODY$
BEGIN
    RETURN QUERY SELECT flightid
                   FROM flight
                  WHERE flightdate &gt;= $1
                    AND flightdate &lt; ($1 + 1);

    -- Since execution is not finished, we can check whether rows were returned
    -- and raise exception if not.
    IF NOT FOUND THEN
        RAISE EXCEPTION 'No flight at %.', $1;
    END IF;

    RETURN;
 END;
$BODY$
LANGUAGE plpgsql;

-- Returns available flights or raises exception if there are no
-- available flights.
SELECT * FROM get_available_flightid(CURRENT_DATE);
</programlisting>
     </para>

     <note>
      <para>
       The current implementation of <command>RETURN NEXT</command>
       and <command>RETURN QUERY</command> stores the entire result set
       before returning from the function, as discussed above.  That
       means that if a <application>PL/pgSQL</application> function produces a
       very large result set, performance might be poor: data will be
       written to disk to avoid memory exhaustion, but the function
       itself will not return until the entire result set has been
       generated.  A future version of <application>PL/pgSQL</application> might
       allow users to define set-returning functions
       that do not have this limitation.  Currently, the point at
       which data begins being written to disk is controlled by the
       <xref linkend="guc-work-mem"/>
       configuration variable.  Administrators who have sufficient
       memory to store larger result sets in memory should consider
       increasing this parameter.
      </para>
     </note>
    </sect3>
   </sect2>

   <sect2 id="plpgsql-statements-returning-procedure">
    <title>Returning from a Procedure</title>

    <para>
     A procedure does not have a return value.  A procedure can therefore end
     without a <command>RETURN</command> statement.  If you wish to use
     a <command>RETURN</command> statement to exit the code early, write
     just <command>RETURN</command> with no expression.
    </para>

    <para>
     If the procedure has output parameters, the final values of the output
     parameter variables will be returned to the caller.
    </para>
   </sect2>

   <sect2 id="plpgsql-statements-calling-procedure">
    <title>Calling a Procedure</title>

    <para>
     A <application>PL/pgSQL</application> function, procedure,
     or <command>DO</command> block can call a procedure
     using <command>CALL</command>.  Output parameters are handled
     differently from the way that <command>CALL</command> works in plain
     SQL.  Each <literal>OUT</literal> or <literal>INOUT</literal>
     parameter of the procedure must
     correspond to a variable in the <command>CALL</command> statement, and
     whatever the procedure returns is assigned back to that variable after
     it returns.  For example:
<programlisting>
CREATE PROCEDURE triple(INOUT x int)
LANGUAGE plpgsql
AS $$
BEGIN
    x := x * 3;
END;
$$;

DO $$
DECLARE myvar int := 5;
BEGIN
  CALL triple(myvar);
  RAISE NOTICE 'myvar = %', myvar;  -- prints 15
END;
$$;
</programlisting>
     The variable corresponding to an output parameter can be a simple
     variable or a field of a composite-type variable.  Currently,
     it cannot be an element of an array.
    </para>
   </sect2>

   <sect2 id="plpgsql-conditionals">
    <title>Conditionals</title>

    <para>
     <command>IF</command> and <command>CASE</command> statements let you execute
     alternative commands based on certain conditions.
     <application>PL/pgSQL</application> has three forms of <command>IF</command>:
    <itemizedlist>
     <listitem>
      <para><literal>IF ... THEN ... END IF</literal></para>
     </listitem>
     <listitem>
      <para><literal>IF ... THEN ... ELSE ... END IF</literal></para>
     </listitem>
     <listitem>
      <para><literal>IF ... THEN ... ELSIF ... THEN ... ELSE ... END IF</literal></para>
     </listitem>
    </itemizedlist>

    and two forms of <command>CASE</command>:
    <itemizedlist>
     <listitem>
      <para><literal>CASE ... WHEN ... THEN ... ELSE ... END CASE</literal></para>
     </listitem>
     <listitem>
      <para><literal>CASE WHEN ... THEN ... ELSE ... END CASE</literal></para>
     </listitem>
    </itemizedlist>
    </para>

    <sect3>
     <title><literal>IF-THEN</literal></title>

<synopsis>
IF <replaceable>boolean-expression</replaceable> THEN
    <replaceable>statements</replaceable>
END IF;
</synopsis>

       <para>
        <literal>IF-THEN</literal> statements are the simplest form of
        <literal>IF</literal>. The statements between
        <literal>THEN</literal> and <literal>END IF</literal> will be
        executed if the condition is true. Otherwise, they are
        skipped.
       </para>

       <para>
        Example:
<programlisting>
IF v_user_id &lt;&gt; 0 THEN
    UPDATE users SET email = v_email WHERE user_id = v_user_id;
END IF;
</programlisting>
       </para>
     </sect3>

     <sect3>
      <title><literal>IF-THEN-ELSE</literal></title>

<synopsis>
IF <replaceable>boolean-expression</replaceable> THEN
    <replaceable>statements</replaceable>
ELSE
    <replaceable>statements</replaceable>
END IF;
</synopsis>

       <para>
        <literal>IF-THEN-ELSE</literal> statements add to
        <literal>IF-THEN</literal> by letting you specify an
        alternative set of statements that should be executed if the
        condition is not true.  (Note this includes the case where the
        condition evaluates to NULL.)
       </para>

       <para>
        Examples:
<programlisting>
IF parentid IS NULL OR parentid = ''
THEN
    RETURN fullname;
ELSE
    RETURN hp_true_filename(parentid) || '/' || fullname;
END IF;
</programlisting>

<programlisting>
IF v_count &gt; 0 THEN
    INSERT INTO users_count (count) VALUES (v_count);
    RETURN 't';
ELSE
    RETURN 'f';
END IF;
</programlisting>
     </para>
    </sect3>

     <sect3>
      <title><literal>IF-THEN-ELSIF</literal></title>

<synopsis>
IF <replaceable>boolean-expression</replaceable> THEN
    <replaceable>statements</replaceable>
<optional> ELSIF <replaceable>boolean-expression</replaceable> THEN
    <replaceable>statements</replaceable>
<optional> ELSIF <replaceable>boolean-expression</replaceable> THEN
    <replaceable>statements</replaceable>
    ...
</optional>
</optional>
<optional> ELSE
    <replaceable>statements</replaceable> </optional>
END IF;
</synopsis>

       <para>
        Sometimes there are more than just two alternatives.
        <literal>IF-THEN-ELSIF</literal> provides a convenient
        method of checking several alternatives in turn.
        The <literal>IF</literal> conditions are tested successively
        until the first one that is true is found.  Then the
        associated statement(s) are executed, after which control
        passes to the next statement after <literal>END IF</literal>.
        (Any subsequent <literal>IF</literal> conditions are <emphasis>not</emphasis>
        tested.)  If none of the <literal>IF</literal> conditions is true,
        then the <literal>ELSE</literal> block (if any) is executed.
       </para>

       <para>
        Here is an example:

<programlisting>
IF number = 0 THEN
    result := 'zero';
ELSIF number &gt; 0 THEN
    result := 'positive';
ELSIF number &lt; 0 THEN
    result := 'negative';
ELSE
    -- hmm, the only other possibility is that number is null
    result := 'NULL';
END IF;
</programlisting>
       </para>

       <para>
        The key word <literal>ELSIF</literal> can also be spelled
        <literal>ELSEIF</literal>.
       </para>

       <para>
        An alternative way of accomplishing the same task is to nest
        <literal>IF-THEN-ELSE</literal> statements, as in the
        following example:

<programlisting>
IF demo_row.sex = 'm' THEN
    pretty_sex := 'man';
ELSE
    IF demo_row.sex = 'f' THEN
        pretty_sex := 'woman';
    END IF;
END IF;
</programlisting>
       </para>

       <para>
        However, this method requires writing a matching <literal>END IF</literal>
        for each <literal>IF</literal>, so it is much more cumbersome than
        using <literal>ELSIF</literal> when there are many alternatives.
       </para>
     </sect3>

     <sect3>
      <title>Simple <literal>CASE</literal></title>

<synopsis>
CASE <replaceable>search-expression</replaceable>
    WHEN <replaceable>expression</replaceable> <optional>, <replaceable>expression</replaceable> <optional> ... </optional></optional> THEN
      <replaceable>statements</replaceable>
  <optional> WHEN <replaceable>expression</replaceable> <optional>, <replaceable>expression</replaceable> <optional> ... </optional></optional> THEN
      <replaceable>statements</replaceable>
    ... </optional>
  <optional> ELSE
      <replaceable>statements</replaceable> </optional>
END CASE;
</synopsis>

      <para>
       The simple form of <command>CASE</command> provides conditional execution
       based on equality of operands.  The <replaceable>search-expression</replaceable>
       is evaluated (once) and successively compared to each
       <replaceable>expression</replaceable> in the <literal>WHEN</literal> clauses.
       If a match is found, then the corresponding
       <replaceable>statements</replaceable> are executed, and then control
       passes to the next statement after <literal>END CASE</literal>.  (Subsequent
       <literal>WHEN</literal> expressions are not evaluated.)  If no match is
       found, the <literal>ELSE</literal> <replaceable>statements</replaceable> are
       executed; but if <literal>ELSE</literal> is not present, then a
       <literal>CASE_NOT_FOUND</literal> exception is raised.
      </para>

      <para>
       Here is a simple example:

<programlisting>
CASE x
    WHEN 1, 2 THEN
        msg := 'one or two';
    ELSE
        msg := 'other value than one or two';
END CASE;
</programlisting>
      </para>
     </sect3>

     <sect3>
      <title>Searched <literal>CASE</literal></title>

<synopsis>
CASE
    WHEN <replaceable>boolean-expression</replaceable> THEN
      <replaceable>statements</replaceable>
  <optional> WHEN <replaceable>boolean-expression</replaceable> THEN
      <replaceable>statements</replaceable>
    ... </optional>
  <optional> ELSE
      <replaceable>statements</replaceable> </optional>
END CASE;
</synopsis>

      <para>
       The searched form of <command>CASE</command> provides conditional execution
       based on truth of Boolean expressions.  Each <literal>WHEN</literal> clause's
       <replaceable>boolean-expression</replaceable> is evaluated in turn,
       until one is found that yields <literal>true</literal>.  Then the
       corresponding <replaceable>statements</replaceable> are executed, and
       then control passes to the next statement after <literal>END CASE</literal>.
       (Subsequent <literal>WHEN</literal> expressions are not evaluated.)
       If no true result is found, the <literal>ELSE</literal>
       <replaceable>statements</replaceable> are executed;
       but if <literal>ELSE</literal> is not present, then a
       <literal>CASE_NOT_FOUND</literal> exception is raised.
      </para>

      <para>
       Here is an example:

<programlisting>
CASE
    WHEN x BETWEEN 0 AND 10 THEN
        msg := 'value is between zero and ten';
    WHEN x BETWEEN 11 AND 20 THEN
        msg := 'value is between eleven and twenty';
END CASE;
</programlisting>
      </para>

      <para>
       This form of <command>CASE</command> is entirely equivalent to
       <literal>IF-THEN-ELSIF</literal>, except for the rule that reaching
       an omitted <literal>ELSE</literal> clause results in an error rather
       than doing nothing.
      </para>

     </sect3>
   </sect2>

   <sect2 id="plpgsql-control-structures-loops">
    <title>Simple Loops</title>

    <indexterm zone="plpgsql-control-structures-loops">
     <primary>loop</primary>
     <secondary>in PL/pgSQL</secondary>
    </indexterm>

    <para>
     With the <literal>LOOP</literal>, <literal>EXIT</literal>,
     <literal>CONTINUE</literal>, <literal>WHILE</literal>, <literal>FOR</literal>,
     and <literal>FOREACH</literal> statements, you can arrange for your
     <application>PL/pgSQL</application> function to repeat a series of commands.
    </para>

    <sect3>
     <title><literal>LOOP</literal></title>

<synopsis>
<optional> &lt;&lt;<replaceable>label</replaceable>&gt;&gt; </optional>
LOOP
    <replaceable>statements</replaceable>
END LOOP <optional> <replaceable>label</replaceable> </optional>;
</synopsis>

     <para>
      <literal>LOOP</literal> defines an unconditional loop that is repeated
      indefinitely until terminated by an <literal>EXIT</literal> or
      <command>RETURN</command> statement.  The optional
      <replaceable>label</replaceable> can be used by <literal>EXIT</literal>
      and <literal>CONTINUE</literal> statements within nested loops to
      specify which loop those statements refer to.
     </para>
    </sect3>

     <sect3>
      <title><literal>EXIT</literal></title>

     <indexterm>
      <primary>EXIT</primary>
      <secondary>in PL/pgSQL</secondary>
     </indexterm>

<synopsis>
EXIT <optional> <replaceable>label</replaceable> </optional> <optional> WHEN <replaceable>boolean-expression</replaceable> </optional>;
</synopsis>

       <para>
        If no <replaceable>label</replaceable> is given, the innermost
        loop is terminated and the statement following <literal>END
        LOOP</literal> is executed next.  If <replaceable>label</replaceable>
        is given, it must be the label of the current or some outer
        level of nested loop or block. Then the named loop or block is
        terminated and control continues with the statement after the
        loop's/block's corresponding <literal>END</literal>.
       </para>

       <para>
        If <literal>WHEN</literal> is specified, the loop exit occurs only if
        <replaceable>boolean-expression</replaceable> is true. Otherwise, control passes
        to the statement after <literal>EXIT</literal>.
       </para>

       <para>
        <literal>EXIT</literal> can be used with all types of loops; it is
        not limited to use with unconditional loops.
       </para>

       <para>
        When used with a
        <literal>BEGIN</literal> block, <literal>EXIT</literal> passes
        control to the next statement after the end of the block.
        Note that a label must be used for this purpose; an unlabeled
        <literal>EXIT</literal> is never considered to match a
        <literal>BEGIN</literal> block.  (This is a change from
        pre-8.4 releases of <productname>PostgreSQL</productname>, which
        would allow an unlabeled <literal>EXIT</literal> to match
        a <literal>BEGIN</literal> block.)
       </para>

       <para>
        Examples:
<programlisting>
LOOP
    -- some computations
    IF count &gt; 0 THEN
        EXIT;  -- exit loop
    END IF;
END LOOP;

LOOP
    -- some computations
    EXIT WHEN count &gt; 0;  -- same result as previous example
END LOOP;

&lt;&lt;ablock&gt;&gt;
BEGIN
    -- some computations
    IF stocks &gt; 100000 THEN
        EXIT ablock;  -- causes exit from the BEGIN block
    END IF;
    -- computations here will be skipped when stocks &gt; 100000
END;
</programlisting>
       </para>
     </sect3>

     <sect3>
      <title><literal>CONTINUE</literal></title>

     <indexterm>
      <primary>CONTINUE</primary>
      <secondary>in PL/pgSQL</secondary>
     </indexterm>

<synopsis>
CONTINUE <optional> <replaceable>label</replaceable> </optional> <optional> WHEN <replaceable>boolean-expression</replaceable> </optional>;
</synopsis>

       <para>
        If no <replaceable>label</replaceable> is given, the next iteration of
        the innermost loop is begun. That is, all statements remaining
        in the loop body are skipped, and control returns
        to the loop control expression (if any) to determine whether
        another loop iteration is needed.
        If <replaceable>label</replaceable> is present, it
        specifies the label of the loop whose execution will be
        continued.
       </para>

       <para>
        If <literal>WHEN</literal> is specified, the next iteration of the
        loop is begun only if <replaceable>boolean-expression</replaceable> is
        true. Otherwise, control passes to the statement after
        <literal>CONTINUE</literal>.
       </para>

       <para>
        <literal>CONTINUE</literal> can be used with all types of loops; it
        is not limited to use with unconditional loops.
       </para>

       <para>
        Examples:
<programlisting>
LOOP
    -- some computations
    EXIT WHEN count &gt; 100;
    CONTINUE WHEN count &lt; 50;
    -- some computations for count IN [50 .. 100]
END LOOP;
</programlisting>
       </para>
     </sect3>


     <sect3>
      <title><literal>WHILE</literal></title>

     <indexterm>
      <primary>WHILE</primary>
      <secondary>in PL/pgSQL</secondary>
     </indexterm>

<synopsis>
<optional> &lt;&lt;<replaceable>label</replaceable>&gt;&gt; </optional>
WHILE <replaceable>boolean-expression</replaceable> LOOP
    <replaceable>statements</replaceable>
END LOOP <optional> <replaceable>label</replaceable> </optional>;
</synopsis>

       <para>
        The <literal>WHILE</literal> statement repeats a
        sequence of statements so long as the
        <replaceable>boolean-expression</replaceable>
        evaluates to true.  The expression is checked just before
        each entry to the loop body.
       </para>

       <para>
        For example:
<programlisting>
WHILE amount_owed &gt; 0 AND gift_certificate_balance &gt; 0 LOOP
    -- some computations here
END LOOP;

WHILE NOT done LOOP
    -- some computations here
END LOOP;
</programlisting>
       </para>
     </sect3>

     <sect3 id="plpgsql-integer-for">
      <title><literal>FOR</literal> (Integer Variant)</title>

<synopsis>
<optional> &lt;&lt;<replaceable>label</replaceable>&gt;&gt; </optional>
FOR <replaceable>name</replaceable> IN <optional> REVERSE </optional> <replaceable>expression</replaceable> .. <replaceable>expression</replaceable> <optional> BY <replaceable>expression</replaceable> </optional> LOOP
    <replaceable>statements</replaceable>
END LOOP <optional> <replaceable>label</replaceable> </optional>;
</synopsis>

       <para>
        This form of <literal>FOR</literal> creates a loop that iterates over a range
        of integer values. The variable
        <replaceable>name</replaceable> is automatically defined as type
        <type>integer</type> and exists only inside the loop (any existing
        definition of the variable name is ignored within the loop).
        The two expressions giving
        the lower and upper bound of the range are evaluated once when entering
        the loop. If the <literal>BY</literal> clause isn't specified the iteration
        step is 1, otherwise it's the value specified in the <literal>BY</literal>
        clause, which again is evaluated once on loop entry.
        If <literal>REVERSE</literal> is specified then the step value is
        subtracted, rather than added, after each iteration.
       </para>

       <para>
        Some examples of integer <literal>FOR</literal> loops:
<programlisting>
FOR i IN 1..10 LOOP
    -- i will take on the values 1,2,3,4,5,6,7,8,9,10 within the loop
END LOOP;

FOR i IN REVERSE 10..1 LOOP
    -- i will take on the values 10,9,8,7,6,5,4,3,2,1 within the loop
END LOOP;

FOR i IN REVERSE 10..1 BY 2 LOOP
    -- i will take on the values 10,8,6,4,2 within the loop
END LOOP;
</programlisting>
       </para>

       <para>
        If the lower bound is greater than the upper bound (or less than,
        in the <literal>REVERSE</literal> case), the loop body is not
        executed at all.  No error is raised.
       </para>

       <para>
        If a <replaceable>label</replaceable> is attached to the
        <literal>FOR</literal> loop then the integer loop variable can be
        referenced with a qualified name, using that
        <replaceable>label</replaceable>.
       </para>
     </sect3>
   </sect2>

   <sect2 id="plpgsql-records-iterating">
    <title>Looping through Query Results</title>

    <para>
     Using a different type of <literal>FOR</literal> loop, you can iterate through
     the results of a query and manipulate that data
     accordingly. The syntax is:
<synopsis>
<optional> &lt;&lt;<replaceable>label</replaceable>&gt;&gt; </optional>
FOR <replaceable>target</replaceable> IN <replaceable>query</replaceable> LOOP
    <replaceable>statements</replaceable>
END LOOP <optional> <replaceable>label</replaceable> </optional>;
</synopsis>
     The <replaceable>target</replaceable> is a record variable, row variable,
     or comma-separated list of scalar variables.
     The <replaceable>target</replaceable> is successively assigned each row
     resulting from the <replaceable>query</replaceable> and the loop body is
     executed for each row. Here is an example:
<programlisting>
CREATE FUNCTION refresh_mviews() RETURNS integer AS $$
DECLARE
    mviews RECORD;
BEGIN
    RAISE NOTICE 'Refreshing all materialized views...';

    FOR mviews IN
       SELECT n.nspname AS mv_schema,
              c.relname AS mv_name,
              pg_catalog.pg_get_userbyid(c.relowner) AS owner
         FROM pg_catalog.pg_class c
    LEFT JOIN pg_catalog.pg_namespace n ON (n.oid = c.relnamespace)
        WHERE c.relkind = 'm'
     ORDER BY 1
    LOOP

        -- Now "mviews" has one record with information about the materialized view

        RAISE NOTICE 'Refreshing materialized view %.% (owner: %)...',
                     quote_ident(mviews.mv_schema),
                     quote_ident(mviews.mv_name),
                     quote_ident(mviews.owner);
        EXECUTE format('REFRESH MATERIALIZED VIEW %I.%I', mviews.mv_schema, mviews.mv_name);
    END LOOP;

    RAISE NOTICE 'Done refreshing materialized views.';
    RETURN 1;
END;
$$ LANGUAGE plpgsql;
</programlisting>

     If the loop is terminated by an <literal>EXIT</literal> statement, the last
     assigned row value is still accessible after the loop.
    </para>

    <para>
     The <replaceable>query</replaceable> used in this type of <literal>FOR</literal>
     statement can be any SQL command that returns rows to the caller:
     <command>SELECT</command> is the most common case,
     but you can also use <command>INSERT</command>, <command>UPDATE</command>, or
     <command>DELETE</command> with a <literal>RETURNING</literal> clause.  Some utility
     commands such as <command>EXPLAIN</command> will work too.
    </para>

    <para>
     <application>PL/pgSQL</application> variables are replaced by query parameters,
     and the query plan is cached for possible re-use, as discussed in
     detail in <xref linkend="plpgsql-var-subst"/> and
     <xref linkend="plpgsql-plan-caching"/>.
    </para>

    <para>
     The <literal>FOR-IN-EXECUTE</literal> statement is another way to iterate over
     rows:
<synopsis>
<optional> &lt;&lt;<replaceable>label</replaceable>&gt;&gt; </optional>
FOR <replaceable>target</replaceable> IN EXECUTE <replaceable>text_expression</replaceable> <optional> USING <replaceable>expression</replaceable> <optional>, ... </optional> </optional> LOOP
    <replaceable>statements</replaceable>
END LOOP <optional> <replaceable>label</replaceable> </optional>;
</synopsis>
     This is like the previous form, except that the source query
     is specified as a string expression, which is evaluated and replanned
     on each entry to the <literal>FOR</literal> loop.  This allows the programmer to
     choose the speed of a preplanned query or the flexibility of a dynamic
     query, just as with a plain <command>EXECUTE</command> statement.
     As with <command>EXECUTE</command>, parameter values can be inserted
     into the dynamic command via <literal>USING</literal>.
    </para>

    <para>
     Another way to specify the query whose results should be iterated
     through is to declare it as a cursor.  This is described in
     <xref linkend="plpgsql-cursor-for-loop"/>.
    </para>
   </sect2>

   <sect2 id="plpgsql-foreach-array">
    <title>Looping through Arrays</title>

    <para>
     The <literal>FOREACH</literal> loop is much like a <literal>FOR</literal> loop,
     but instead of iterating through the rows returned by an SQL query,
     it iterates through the elements of an array value.
     (In general, <literal>FOREACH</literal> is meant for looping through
     components of a composite-valued expression; variants for looping
     through composites besides arrays may be added in future.)
     The <literal>FOREACH</literal> statement to loop over an array is:

<synopsis>
<optional> &lt;&lt;<replaceable>label</replaceable>&gt;&gt; </optional>
FOREACH <replaceable>target</replaceable> <optional> SLICE <replaceable>number</replaceable> </optional> IN ARRAY <replaceable>expression</replaceable> LOOP
    <replaceable>statements</replaceable>
END LOOP <optional> <replaceable>label</replaceable> </optional>;
</synopsis>
    </para>

    <para>
     Without <literal>SLICE</literal>, or if <literal>SLICE 0</literal> is specified,
     the loop iterates through individual elements of the array produced
     by evaluating the <replaceable>expression</replaceable>.
     The <replaceable>target</replaceable> variable is assigned each
     element value in sequence, and the loop body is executed for each element.
     Here is an example of looping through the elements of an integer
     array:

<programlisting>
CREATE FUNCTION sum(int[]) RETURNS int8 AS $$
DECLARE
  s int8 := 0;
  x int;
BEGIN
  FOREACH x IN ARRAY $1
  LOOP
    s := s + x;
  END LOOP;
  RETURN s;
END;
$$ LANGUAGE plpgsql;
</programlisting>

     The elements are visited in storage order, regardless of the number of
     array dimensions.  Although the <replaceable>target</replaceable> is
     usually just a single variable, it can be a list of variables when
     looping through an array of composite values (records).  In that case,
     for each array element, the variables are assigned from successive
     columns of the composite value.
    </para>

    <para>
     With a positive <literal>SLICE</literal> value, <literal>FOREACH</literal>
     iterates through slices of the array rather than single elements.
     The <literal>SLICE</literal> value must be an integer constant not larger
     than the number of dimensions of the array.  The
     <replaceable>target</replaceable> variable must be an array,
     and it receives successive slices of the array value, where each slice
     is of the number of dimensions specified by <literal>SLICE</literal>.
     Here is an example of iterating through one-dimensional slices:

<programlisting>
CREATE FUNCTION scan_rows(int[]) RETURNS void AS $$
DECLARE
  x int[];
BEGIN
  FOREACH x SLICE 1 IN ARRAY $1
  LOOP
    RAISE NOTICE 'row = %', x;
  END LOOP;
END;
$$ LANGUAGE plpgsql;

SELECT scan_rows(ARRAY[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]);

NOTICE:  row = {1,2,3}
NOTICE:  row = {4,5,6}
NOTICE:  row = {7,8,9}
NOTICE:  row = {10,11,12}
</programlisting>
    </para>
   </sect2>

   <sect2 id="plpgsql-error-trapping">
    <title>Trapping Errors</title>

    <indexterm>
     <primary>exceptions</primary>
     <secondary>in PL/pgSQL</secondary>
    </indexterm>

    <para>
     By default, any error occurring in a <application>PL/pgSQL</application>
     function aborts execution of the function and the
     surrounding transaction.  You can trap errors and recover
     from them by using a <command>BEGIN</command> block with an
     <literal>EXCEPTION</literal> clause.  The syntax is an extension of the
     normal syntax for a <command>BEGIN</command> block:

<synopsis>
<optional> &lt;&lt;<replaceable>label</replaceable>&gt;&gt; </optional>
<optional> DECLARE
    <replaceable>declarations</replaceable> </optional>
BEGIN
    <replaceable>statements</replaceable>
EXCEPTION
    WHEN <replaceable>condition</replaceable> <optional> OR <replaceable>condition</replaceable> ... </optional> THEN
        <replaceable>handler_statements</replaceable>
    <optional> WHEN <replaceable>condition</replaceable> <optional> OR <replaceable>condition</replaceable> ... </optional> THEN
          <replaceable>handler_statements</replaceable>
      ... </optional>
END;
</synopsis>
    </para>

    <para>
     If no error occurs, this form of block simply executes all the
     <replaceable>statements</replaceable>, and then control passes
     to the next statement after <literal>END</literal>.  But if an error
     occurs within the <replaceable>statements</replaceable>, further
     processing of the <replaceable>statements</replaceable> is
     abandoned, and control passes to the <literal>EXCEPTION</literal> list.
     The list is searched for the first <replaceable>condition</replaceable>
     matching the error that occurred.  If a match is found, the
     corresponding <replaceable>handler_statements</replaceable> are
     executed, and then control passes to the next statement after
     <literal>END</literal>.  If no match is found, the error propagates out
     as though the <literal>EXCEPTION</literal> clause were not there at all:
     the error can be caught by an enclosing block with
     <literal>EXCEPTION</literal>, or if there is none it aborts processing
     of the function.
    </para>

    <para>
     The <replaceable>condition</replaceable> names can be any of
     those shown in <xref linkend="errcodes-appendix"/>.  A category
     name matches any error within its category.  The special
     condition name <literal>OTHERS</literal> matches every error type except
     <literal>QUERY_CANCELED</literal> and <literal>ASSERT_FAILURE</literal>.
     (It is possible, but often unwise, to trap those two error types
     by name.)  Condition names are
     not case-sensitive.  Also, an error condition can be specified
     by <literal>SQLSTATE</literal> code; for example these are equivalent:
<programlisting>
WHEN division_by_zero THEN ...
WHEN SQLSTATE '22012' THEN ...
</programlisting>
    </para>

    <para>
     If a new error occurs within the selected
     <replaceable>handler_statements</replaceable>, it cannot be caught
     by this <literal>EXCEPTION</literal> clause, but is propagated out.
     A surrounding <literal>EXCEPTION</literal> clause could catch it.
    </para>

    <para>
     When an error is caught by an <literal>EXCEPTION</literal> clause,
     the local variables of the <application>PL/pgSQL</application> function
     remain as they were when the error occurred, but all changes
     to persistent database state within the block are rolled back.
     As an example, consider this fragment:

<programlisting>
INSERT INTO mytab(firstname, lastname) VALUES('Tom', 'Jones');
BEGIN
    UPDATE mytab SET firstname = 'Joe' WHERE lastname = 'Jones';
    x := x + 1;
    y := x / 0;
EXCEPTION
    WHEN division_by_zero THEN
        RAISE NOTICE 'caught division_by_zero';
        RETURN x;
END;
</programlisting>

     When control reaches the assignment to <literal>y</literal>, it will
     fail with a <literal>division_by_zero</literal> error.  This will be caught by
     the <literal>EXCEPTION</literal> clause.  The value returned in the
     <command>RETURN</command> statement will be the incremented value of
     <literal>x</literal>, but the effects of the <command>UPDATE</command> command will
     have been rolled back.  The <command>INSERT</command> command preceding the
     block is not rolled back, however, so the end result is that the database
     contains <literal>Tom Jones</literal> not <literal>Joe Jones</literal>.
    </para>

    <tip>
     <para>
      A block containing an <literal>EXCEPTION</literal> clause is significantly
      more expensive to enter and exit than a block without one.  Therefore,
      don't use <literal>EXCEPTION</literal> without need.
     </para>
    </tip>

    <example id="plpgsql-upsert-example">
    <title>Exceptions with <command>UPDATE</command>/<command>INSERT</command></title>
    <para>

    This example uses exception handling to perform either
    <command>UPDATE</command> or <command>INSERT</command>, as appropriate.  It is
    recommended that applications use <command>INSERT</command> with
    <literal>ON CONFLICT DO UPDATE</literal> rather than actually using
    this pattern.  This example serves primarily to illustrate use of
    <application>PL/pgSQL</application> control flow structures:

<programlisting>
CREATE TABLE db (a INT PRIMARY KEY, b TEXT);

CREATE FUNCTION merge_db(key INT, data TEXT) RETURNS VOID AS
$$
BEGIN
    LOOP
        -- first try to update the key
        UPDATE db SET b = data WHERE a = key;
        IF found THEN
            RETURN;
        END IF;
        -- not there, so try to insert the key
        -- if someone else inserts the same key concurrently,
        -- we could get a unique-key failure
        BEGIN
            INSERT INTO db(a,b) VALUES (key, data);
            RETURN;
        EXCEPTION WHEN unique_violation THEN
            -- Do nothing, and loop to try the UPDATE again.
        END;
    END LOOP;
END;
$$
LANGUAGE plpgsql;

SELECT merge_db(1, 'david');
SELECT merge_db(1, 'dennis');
</programlisting>

     This coding assumes the <literal>unique_violation</literal> error is caused by
     the <command>INSERT</command>, and not by, say, an <command>INSERT</command> in a
     trigger function on the table.  It might also misbehave if there is
     more than one unique index on the table, since it will retry the
     operation regardless of which index caused the error.
     More safety could be had by using the
     features discussed next to check that the trapped error was the one
     expected.
    </para>
    </example>

   <sect3 id="plpgsql-exception-diagnostics">
    <title>Obtaining Information about an Error</title>

    <para>
     Exception handlers frequently need to identify the specific error that
     occurred.  There are two ways to get information about the current
     exception in <application>PL/pgSQL</application>: special variables and the
     <command>GET STACKED DIAGNOSTICS</command> command.
    </para>

    <para>
     Within an exception handler, the special variable
     <varname>SQLSTATE</varname> contains the error code that corresponds to
     the exception that was raised (refer to <xref linkend="errcodes-table"/>
     for a list of possible error codes). The special variable
     <varname>SQLERRM</varname> contains the error message associated with the
     exception. These variables are undefined outside exception handlers.
    </para>

    <para>
     Within an exception handler, one may also retrieve
     information about the current exception by using the
     <command>GET STACKED DIAGNOSTICS</command> command, which has the form:

<synopsis>
GET STACKED DIAGNOSTICS <replaceable>variable</replaceable> { = | := } <replaceable>item</replaceable> <optional> , ... </optional>;
</synopsis>

     Each <replaceable>item</replaceable> is a key word identifying a status
     value to be assigned to the specified <replaceable>variable</replaceable>
     (which should be of the right data type to receive it).  The currently
     available status items are shown
     in <xref linkend="plpgsql-exception-diagnostics-values"/>.
    </para>

     <table id="plpgsql-exception-diagnostics-values">
      <title>Error Diagnostics Items</title>
      <tgroup cols="3">
       <colspec colname="col1" colwidth="2*"/>
       <colspec colname="col2" colwidth="1*"/>
       <colspec colname="col3" colwidth="2*"/>
       <thead>
        <row>
         <entry>Name</entry>
         <entry>Type</entry>
         <entry>Description</entry>
        </row>
       </thead>
       <tbody>
        <row>
         <entry><literal>RETURNED_SQLSTATE</literal></entry>
         <entry><type>text</type></entry>
         <entry>the SQLSTATE error code of the exception</entry>
        </row>
        <row>
         <entry><literal>COLUMN_NAME</literal></entry>
         <entry><type>text</type></entry>
         <entry>the name of the column related to exception</entry>
        </row>
        <row>
         <entry><literal>CONSTRAINT_NAME</literal></entry>
         <entry><type>text</type></entry>
         <entry>the name of the constraint related to exception</entry>
        </row>
        <row>
         <entry><literal>PG_DATATYPE_NAME</literal></entry>
         <entry><type>text</type></entry>
         <entry>the name of the data type related to exception</entry>
        </row>
        <row>
         <entry><literal>MESSAGE_TEXT</literal></entry>
         <entry><type>text</type></entry>
         <entry>the text of the exception's primary message</entry>
        </row>
        <row>
         <entry><literal>TABLE_NAME</literal></entry>
         <entry><type>text</type></entry>
         <entry>the name of the table related to exception</entry>
        </row>
        <row>
         <entry><literal>SCHEMA_NAME</literal></entry>
         <entry><type>text</type></entry>
         <entry>the name of the schema related to exception</entry>
        </row>
        <row>
         <entry><literal>PG_EXCEPTION_DETAIL</literal></entry>
         <entry><type>text</type></entry>
         <entry>the text of the exception's detail message, if any</entry>
        </row>
        <row>
         <entry><literal>PG_EXCEPTION_HINT</literal></entry>
         <entry><type>text</type></entry>
         <entry>the text of the exception's hint message, if any</entry>
        </row>
        <row>
         <entry><literal>PG_EXCEPTION_CONTEXT</literal></entry>
         <entry><type>text</type></entry>
         <entry>line(s) of text describing the call stack at the time of the
          exception (see <xref linkend="plpgsql-call-stack"/>)</entry>
        </row>
       </tbody>
      </tgroup>
     </table>

    <para>
     If the exception did not set a value for an item, an empty string
     will be returned.
    </para>

    <para>
     Here is an example:
<programlisting>
DECLARE
  text_var1 text;
  text_var2 text;
  text_var3 text;
BEGIN
  -- some processing which might cause an exception
  ...
EXCEPTION WHEN OTHERS THEN
  GET STACKED DIAGNOSTICS text_var1 = MESSAGE_TEXT,
                          text_var2 = PG_EXCEPTION_DETAIL,
                          text_var3 = PG_EXCEPTION_HINT;
END;
</programlisting>
    </para>
   </sect3>
  </sect2>

  <sect2 id="plpgsql-call-stack">
   <title>Obtaining Execution Location Information</title>

   <para>
    The <command>GET DIAGNOSTICS</command> command, previously described
    in <xref linkend="plpgsql-statements-diagnostics"/>, retrieves information
    about current execution state (whereas the <command>GET STACKED
    DIAGNOSTICS</command> command discussed above reports information about
    the execution state as of a previous error).  Its <literal>PG_CONTEXT</literal>
    status item is useful for identifying the current execution
    location.  <literal>PG_CONTEXT</literal> returns a text string with line(s)
    of text describing the call stack.  The first line refers to the current
    function and currently executing <command>GET DIAGNOSTICS</command>
    command.  The second and any subsequent lines refer to calling functions
    further up the call stack.  For example:

<programlisting>
CREATE OR REPLACE FUNCTION outer_func() RETURNS integer AS $$
BEGIN
  RETURN inner_func();
END;
$$ LANGUAGE plpgsql;

CREATE OR REPLACE FUNCTION inner_func() RETURNS integer AS $$
DECLARE
  stack text;
BEGIN
  GET DIAGNOSTICS stack = PG_CONTEXT;
  RAISE NOTICE E'--- Call Stack ---\n%', stack;
  RETURN 1;
END;
$$ LANGUAGE plpgsql;

SELECT outer_func();

NOTICE:  --- Call Stack ---
PL/pgSQL function inner_func() line 5 at GET DIAGNOSTICS
PL/pgSQL function outer_func() line 3 at RETURN
CONTEXT:  PL/pgSQL function outer_func() line 3 at RETURN
 outer_func
 ------------
           1
(1 row)
</programlisting>

   </para>

   <para>
    <literal>GET STACKED DIAGNOSTICS ... PG_EXCEPTION_CONTEXT</literal>
    returns the same sort of stack trace, but describing the location
    at which an error was detected, rather than the current location.
   </para>
  </sect2>
  </sect1>

  <sect1 id="plpgsql-cursors">
   <title>Cursors</title>

   <indexterm zone="plpgsql-cursors">
    <primary>cursor</primary>
    <secondary>in PL/pgSQL</secondary>
   </indexterm>

   <para>
    Rather than executing a whole query at once, it is possible to set
    up a <firstterm>cursor</firstterm> that encapsulates the query, and then read
    the query result a few rows at a time. One reason for doing this is
    to avoid memory overrun when the result contains a large number of
    rows. (However, <application>PL/pgSQL</application> users do not normally need
    to worry about that, since <literal>FOR</literal> loops automatically use a cursor
    internally to avoid memory problems.) A more interesting usage is to
    return a reference to a cursor that a function has created, allowing the
    caller to read the rows. This provides an efficient way to return
    large row sets from functions.
   </para>

   <sect2 id="plpgsql-cursor-declarations">
    <title>Declaring Cursor Variables</title>

    <para>
     All access to cursors in <application>PL/pgSQL</application> goes through
     cursor variables, which are always of the special data type
     <type>refcursor</type>.  One way to create a cursor variable
     is just to declare it as a variable of type <type>refcursor</type>.
     Another way is to use the cursor declaration syntax,
     which in general is:
<synopsis>
<replaceable>name</replaceable> <optional> <optional> NO </optional> SCROLL </optional> CURSOR <optional> ( <replaceable>arguments</replaceable> ) </optional> FOR <replaceable>query</replaceable>;
</synopsis>
     (<literal>FOR</literal> can be replaced by <literal>IS</literal> for
     <productname>Oracle</productname> compatibility.)
     If <literal>SCROLL</literal> is specified, the cursor will be capable of
     scrolling backward; if <literal>NO SCROLL</literal> is specified, backward
     fetches will be rejected; if neither specification appears, it is
     query-dependent whether backward fetches will be allowed.
     <replaceable>arguments</replaceable>, if specified, is a
     comma-separated list of pairs <literal><replaceable>name</replaceable>
     <replaceable>datatype</replaceable></literal> that define names to be
     replaced by parameter values in the given query.  The actual
     values to substitute for these names will be specified later,
     when the cursor is opened.
    </para>
    <para>
     Some examples:
<programlisting>
DECLARE
    curs1 refcursor;
    curs2 CURSOR FOR SELECT * FROM tenk1;
    curs3 CURSOR (key integer) FOR SELECT * FROM tenk1 WHERE unique1 = key;
</programlisting>
     All three of these variables have the data type <type>refcursor</type>,
     but the first can be used with any query, while the second has
     a fully specified query already <firstterm>bound</firstterm> to it, and the last
     has a parameterized query bound to it.  (<literal>key</literal> will be
     replaced by an integer parameter value when the cursor is opened.)
     The variable <literal>curs1</literal>
     is said to be <firstterm>unbound</firstterm> since it is not bound to
     any particular query.
    </para>

    <para>
     The <literal>SCROLL</literal> option cannot be used when the cursor's
     query uses <literal>FOR UPDATE/SHARE</literal>.  Also, it is
     best to use <literal>NO SCROLL</literal> with a query that involves
     volatile functions.  The implementation of <literal>SCROLL</literal>
     assumes that re-reading the query's output will give consistent
     results, which a volatile function might not do.
    </para>
   </sect2>

   <sect2 id="plpgsql-cursor-opening">
    <title>Opening Cursors</title>

    <para>
     Before a cursor can be used to retrieve rows, it must be
     <firstterm>opened</firstterm>. (This is the equivalent action to the SQL
     command <command>DECLARE CURSOR</command>.) <application>PL/pgSQL</application> has
     three forms of the <command>OPEN</command> statement, two of which use unbound
     cursor variables while the third uses a bound cursor variable.
    </para>

    <note>
     <para>
      Bound cursor variables can also be used without explicitly opening the cursor,
      via the <command>FOR</command> statement described in
      <xref linkend="plpgsql-cursor-for-loop"/>.
     </para>
    </note>

    <sect3>
     <title><command>OPEN FOR</command> <replaceable>query</replaceable></title>

<synopsis>
OPEN <replaceable>unbound_cursorvar</replaceable> <optional> <optional> NO </optional> SCROLL </optional> FOR <replaceable>query</replaceable>;
</synopsis>

       <para>
        The cursor variable is opened and given the specified query to
        execute.  The cursor cannot be open already, and it must have been
        declared as an unbound cursor variable (that is, as a simple
        <type>refcursor</type> variable).  The query must be a
        <command>SELECT</command>, or something else that returns rows
        (such as <command>EXPLAIN</command>).  The query
        is treated in the same way as other SQL commands in
        <application>PL/pgSQL</application>: <application>PL/pgSQL</application>
        variable names are substituted, and the query plan is cached for
        possible reuse.  When a <application>PL/pgSQL</application>
        variable is substituted into the cursor query, the value that is
        substituted is the one it has at the time of the <command>OPEN</command>;
        subsequent changes to the variable will not affect the cursor's
        behavior.
        The <literal>SCROLL</literal> and <literal>NO SCROLL</literal>
        options have the same meanings as for a bound cursor.
       </para>

       <para>
        An example:
<programlisting>
OPEN curs1 FOR SELECT * FROM foo WHERE key = mykey;
</programlisting>
       </para>
     </sect3>

    <sect3>
     <title><command>OPEN FOR EXECUTE</command></title>

<synopsis>
OPEN <replaceable>unbound_cursorvar</replaceable> <optional> <optional> NO </optional> SCROLL </optional> FOR EXECUTE <replaceable class="command">query_string</replaceable>
                                     <optional> USING <replaceable>expression</replaceable> <optional>, ... </optional> </optional>;
</synopsis>

         <para>
          The cursor variable is opened and given the specified query to
          execute.  The cursor cannot be open already, and it must have been
          declared as an unbound cursor variable (that is, as a simple
          <type>refcursor</type> variable).  The query is specified as a string
          expression, in the same way as in the <command>EXECUTE</command>
          command.  As usual, this gives flexibility so the query plan can vary
          from one run to the next (see <xref linkend="plpgsql-plan-caching"/>),
          and it also means that variable substitution is not done on the
          command string. As with <command>EXECUTE</command>, parameter values
          can be inserted into the dynamic command via
          <literal>format()</literal> and <literal>USING</literal>.
          The <literal>SCROLL</literal> and
          <literal>NO SCROLL</literal> options have the same meanings as for a bound
          cursor.
         </para>

       <para>
        An example:
<programlisting>
OPEN curs1 FOR EXECUTE format('SELECT * FROM %I WHERE col1 = $1',tabname) USING keyvalue;
</programlisting>
        In this example, the table name is inserted into the query via
        <function>format()</function>.  The comparison value for <literal>col1</literal>
        is inserted via a <literal>USING</literal> parameter, so it needs
        no quoting.
       </para>
     </sect3>

    <sect3 id="plpgsql-open-bound-cursor">
     <title>Opening a Bound Cursor</title>

<synopsis>
OPEN <replaceable>bound_cursorvar</replaceable> <optional> ( <optional> <replaceable>argument_name</replaceable> := </optional> <replaceable>argument_value</replaceable> <optional>, ...</optional> ) </optional>;
</synopsis>

         <para>
          This form of <command>OPEN</command> is used to open a cursor
          variable whose query was bound to it when it was declared.  The
          cursor cannot be open already.  A list of actual argument value
          expressions must appear if and only if the cursor was declared to
          take arguments.  These values will be substituted in the query.
         </para>

         <para>
          The query plan for a bound cursor is always considered cacheable;
          there is no equivalent of <command>EXECUTE</command> in this case.
          Notice that <literal>SCROLL</literal> and <literal>NO SCROLL</literal> cannot be
          specified in <command>OPEN</command>, as the cursor's scrolling
          behavior was already determined.
         </para>

         <para>
          Argument values can be passed using either <firstterm>positional</firstterm>
          or <firstterm>named</firstterm> notation.  In positional
          notation, all arguments are specified in order.  In named notation,
          each argument's name is specified using <literal>:=</literal> to
          separate it from the argument expression. Similar to calling
          functions, described in <xref linkend="sql-syntax-calling-funcs"/>, it
          is also allowed to mix positional and named notation.
         </para>

         <para>
          Examples (these use the cursor declaration examples above):
<programlisting>
OPEN curs2;
OPEN curs3(42);
OPEN curs3(key := 42);
</programlisting>
         </para>

         <para>
          Because variable substitution is done on a bound cursor's query,
          there are really two ways to pass values into the cursor: either
          with an explicit argument to <command>OPEN</command>, or implicitly by
          referencing a <application>PL/pgSQL</application> variable in the query.
          However, only variables declared before the bound cursor was
          declared will be substituted into it.  In either case the value to
          be passed is determined at the time of the <command>OPEN</command>.
          For example, another way to get the same effect as the
          <literal>curs3</literal> example above is
<programlisting>
DECLARE
    key integer;
    curs4 CURSOR FOR SELECT * FROM tenk1 WHERE unique1 = key;
BEGIN
    key := 42;
    OPEN curs4;
</programlisting>
         </para>
     </sect3>
   </sect2>

   <sect2 id="plpgsql-cursor-using">
    <title>Using Cursors</title>

    <para>
     Once a cursor has been opened, it can be manipulated with the
     statements described here.
    </para>

    <para>
     These manipulations need not occur in the same function that
     opened the cursor to begin with.  You can return a <type>refcursor</type>
     value out of a function and let the caller operate on the cursor.
     (Internally, a <type>refcursor</type> value is simply the string name
     of a so-called portal containing the active query for the cursor.  This name
     can be passed around, assigned to other <type>refcursor</type> variables,
     and so on, without disturbing the portal.)
    </para>

    <para>
     All portals are implicitly closed at transaction end.  Therefore
     a <type>refcursor</type> value is usable to reference an open cursor
     only until the end of the transaction.
    </para>

    <sect3>
     <title><literal>FETCH</literal></title>

<synopsis>
FETCH <optional> <replaceable>direction</replaceable> { FROM | IN } </optional> <replaceable>cursor</replaceable> INTO <replaceable>target</replaceable>;
</synopsis>

    <para>
     <command>FETCH</command> retrieves the next row from the
     cursor into a target, which might be a row variable, a record
     variable, or a comma-separated list of simple variables, just like
     <command>SELECT INTO</command>.  If there is no next row, the
     target is set to NULL(s).  As with <command>SELECT
     INTO</command>, the special variable <literal>FOUND</literal> can
     be checked to see whether a row was obtained or not.
    </para>

    <para>
     The <replaceable>direction</replaceable> clause can be any of the
     variants allowed in the SQL <xref linkend="sql-fetch"/>
     command except the ones that can fetch
     more than one row; namely, it can be
     <literal>NEXT</literal>,
     <literal>PRIOR</literal>,
     <literal>FIRST</literal>,
     <literal>LAST</literal>,
     <literal>ABSOLUTE</literal> <replaceable>count</replaceable>,
     <literal>RELATIVE</literal> <replaceable>count</replaceable>,
     <literal>FORWARD</literal>, or
     <literal>BACKWARD</literal>.
     Omitting <replaceable>direction</replaceable> is the same
     as specifying <literal>NEXT</literal>.
     In the forms using a <replaceable>count</replaceable>,
     the <replaceable>count</replaceable> can be any integer-valued
     expression (unlike the SQL <command>FETCH</command> command,
     which only allows an integer constant).
     <replaceable>direction</replaceable> values that require moving
     backward are likely to fail unless the cursor was declared or opened
     with the <literal>SCROLL</literal> option.
    </para>

    <para>
     <replaceable>cursor</replaceable> must be the name of a <type>refcursor</type>
     variable that references an open cursor portal.
    </para>

    <para>
     Examples:
<programlisting>
FETCH curs1 INTO rowvar;
FETCH curs2 INTO foo, bar, baz;
FETCH LAST FROM curs3 INTO x, y;
FETCH RELATIVE -2 FROM curs4 INTO x;
</programlisting>
       </para>
     </sect3>

    <sect3>
     <title><literal>MOVE</literal></title>

<synopsis>
MOVE <optional> <replaceable>direction</replaceable> { FROM | IN } </optional> <replaceable>cursor</replaceable>;
</synopsis>

    <para>
     <command>MOVE</command> repositions a cursor without retrieving
     any data. <command>MOVE</command> works exactly like the
     <command>FETCH</command> command, except it only repositions the
     cursor and does not return the row moved to. As with <command>SELECT
     INTO</command>, the special variable <literal>FOUND</literal> can
     be checked to see whether there was a next row to move to.
    </para>

    <para>
     Examples:
<programlisting>
MOVE curs1;
MOVE LAST FROM curs3;
MOVE RELATIVE -2 FROM curs4;
MOVE FORWARD 2 FROM curs4;
</programlisting>
       </para>
     </sect3>

    <sect3>
     <title><literal>UPDATE/DELETE WHERE CURRENT OF</literal></title>

<synopsis>
UPDATE <replaceable>table</replaceable> SET ... WHERE CURRENT OF <replaceable>cursor</replaceable>;
DELETE FROM <replaceable>table</replaceable> WHERE CURRENT OF <replaceable>cursor</replaceable>;
</synopsis>

       <para>
        When a cursor is positioned on a table row, that row can be updated
        or deleted using the cursor to identify the row.  There are
        restrictions on what the cursor's query can be (in particular,
        no grouping) and it's best to use <literal>FOR UPDATE</literal> in the
        cursor.  For more information see the
        <xref linkend="sql-declare"/>
        reference page.
       </para>

       <para>
        An example:
<programlisting>
UPDATE foo SET dataval = myval WHERE CURRENT OF curs1;
</programlisting>
       </para>
     </sect3>

    <sect3>
     <title><literal>CLOSE</literal></title>

<synopsis>
CLOSE <replaceable>cursor</replaceable>;
</synopsis>

       <para>
        <command>CLOSE</command> closes the portal underlying an open
        cursor.  This can be used to release resources earlier than end of
        transaction, or to free up the cursor variable to be opened again.
       </para>

       <para>
        An example:
<programlisting>
CLOSE curs1;
</programlisting>
       </para>
     </sect3>

    <sect3>
     <title>Returning Cursors</title>

       <para>
        <application>PL/pgSQL</application> functions can return cursors to the
        caller. This is useful to return multiple rows or columns,
        especially with very large result sets.  To do this, the function
        opens the cursor and returns the cursor name to the caller (or simply
        opens the cursor using a portal name specified by or otherwise known
        to the caller).  The caller can then fetch rows from the cursor. The
        cursor can be closed by the caller, or it will be closed automatically
        when the transaction closes.
       </para>

       <para>
        The portal name used for a cursor can be specified by the
        programmer or automatically generated.  To specify a portal name,
        simply assign a string to the <type>refcursor</type> variable before
        opening it.  The string value of the <type>refcursor</type> variable
        will be used by <command>OPEN</command> as the name of the underlying portal.
        However, if the <type>refcursor</type> variable is null,
        <command>OPEN</command> automatically generates a name that does not
        conflict with any existing portal, and assigns it to the
        <type>refcursor</type> variable.
       </para>

       <note>
        <para>
         A bound cursor variable is initialized to the string value
         representing its name, so that the portal name is the same as
         the cursor variable name, unless the programmer overrides it
         by assignment before opening the cursor.  But an unbound cursor
         variable defaults to the null value initially, so it will receive
         an automatically-generated unique name, unless overridden.
        </para>
       </note>

       <para>
        The following example shows one way a cursor name can be supplied by
        the caller:

<programlisting>
CREATE TABLE test (col text);
INSERT INTO test VALUES ('123');

CREATE FUNCTION reffunc(refcursor) RETURNS refcursor AS '
BEGIN
    OPEN $1 FOR SELECT col FROM test;
    RETURN $1;
END;
' LANGUAGE plpgsql;

BEGIN;
SELECT reffunc('funccursor');
FETCH ALL IN funccursor;
COMMIT;
</programlisting>
       </para>

       <para>
        The following example uses automatic cursor name generation:

<programlisting>
CREATE FUNCTION reffunc2() RETURNS refcursor AS '
DECLARE
    ref refcursor;
BEGIN
    OPEN ref FOR SELECT col FROM test;
    RETURN ref;
END;
' LANGUAGE plpgsql;

-- need to be in a transaction to use cursors.
BEGIN;
SELECT reffunc2();

      reffunc2
--------------------
 &lt;unnamed cursor 1&gt;
(1 row)

FETCH ALL IN "&lt;unnamed cursor 1&gt;";
COMMIT;
</programlisting>
       </para>

       <para>
        The following example shows one way to return multiple cursors
        from a single function:

<programlisting>
CREATE FUNCTION myfunc(refcursor, refcursor) RETURNS SETOF refcursor AS $$
BEGIN
    OPEN $1 FOR SELECT * FROM table_1;
    RETURN NEXT $1;
    OPEN $2 FOR SELECT * FROM table_2;
    RETURN NEXT $2;
END;
$$ LANGUAGE plpgsql;

-- need to be in a transaction to use cursors.
BEGIN;

SELECT * FROM myfunc('a', 'b');

FETCH ALL FROM a;
FETCH ALL FROM b;
COMMIT;
</programlisting>
       </para>
     </sect3>
   </sect2>

   <sect2 id="plpgsql-cursor-for-loop">
    <title>Looping through a Cursor's Result</title>

    <para>
     There is a variant of the <command>FOR</command> statement that allows
     iterating through the rows returned by a cursor.  The syntax is:

<synopsis>
<optional> &lt;&lt;<replaceable>label</replaceable>&gt;&gt; </optional>
FOR <replaceable>recordvar</replaceable> IN <replaceable>bound_cursorvar</replaceable> <optional> ( <optional> <replaceable>argument_name</replaceable> := </optional> <replaceable>argument_value</replaceable> <optional>, ...</optional> ) </optional> LOOP
    <replaceable>statements</replaceable>
END LOOP <optional> <replaceable>label</replaceable> </optional>;
</synopsis>

     The cursor variable must have been bound to some query when it was
     declared, and it <emphasis>cannot</emphasis> be open already.  The
     <command>FOR</command> statement automatically opens the cursor, and it closes
     the cursor again when the loop exits.  A list of actual argument value
     expressions must appear if and only if the cursor was declared to take
     arguments.  These values will be substituted in the query, in just
     the same way as during an <command>OPEN</command> (see <xref
     linkend="plpgsql-open-bound-cursor"/>).
   </para>

   <para>
     The variable <replaceable>recordvar</replaceable> is automatically
     defined as type <type>record</type> and exists only inside the loop (any
     existing definition of the variable name is ignored within the loop).
     Each row returned by the cursor is successively assigned to this
     record variable and the loop body is executed.
    </para>
   </sect2>

  </sect1>

  <sect1 id="plpgsql-transactions">
   <title>Transaction Management</title>

   <para>
    In procedures invoked by the <command>CALL</command> command
    as well as in anonymous code blocks (<command>DO</command> command),
    it is possible to end transactions using the
    commands <command>COMMIT</command> and <command>ROLLBACK</command>.  A new
    transaction is started automatically after a transaction is ended using
    these commands, so there is no separate <command>START
    TRANSACTION</command> command.  (Note that <command>BEGIN</command> and
    <command>END</command> have different meanings in PL/pgSQL.)
   </para>

   <para>
    Here is a simple example:
<programlisting>
CREATE PROCEDURE transaction_test1()
LANGUAGE plpgsql
AS $$
BEGIN
    FOR i IN 0..9 LOOP
        INSERT INTO test1 (a) VALUES (i);
        IF i % 2 = 0 THEN
            COMMIT;
        ELSE
            ROLLBACK;
        END IF;
    END LOOP;
END;
$$;

CALL transaction_test1();
</programlisting>
   </para>

   <indexterm zone="plpgsql-transaction-chain">
    <primary>chained transactions</primary>
    <secondary>in PL/pgSQL</secondary>
   </indexterm>

   <para id="plpgsql-transaction-chain">
    A new transaction starts out with default transaction characteristics such
    as transaction isolation level.  In cases where transactions are committed
    in a loop, it might be desirable to start new transactions automatically
    with the same characteristics as the previous one.  The commands
    <command>COMMIT AND CHAIN</command> and <command>ROLLBACK AND
    CHAIN</command> accomplish this.
   </para>

   <para>
    Transaction control is only possible in <command>CALL</command> or
    <command>DO</command> invocations from the top level or nested
    <command>CALL</command> or <command>DO</command> invocations without any
    other intervening command.  For example, if the call stack is
    <command>CALL proc1()</command> &rarr; <command>CALL proc2()</command>
    &rarr; <command>CALL proc3()</command>, then the second and third
    procedures can perform transaction control actions.  But if the call stack
    is <command>CALL proc1()</command> &rarr; <command>SELECT
    func2()</command> &rarr; <command>CALL proc3()</command>, then the last
    procedure cannot do transaction control, because of the
    <command>SELECT</command> in between.
   </para>

   <para>
    Special considerations apply to cursor loops.  Consider this example:
<programlisting>
CREATE PROCEDURE transaction_test2()
LANGUAGE plpgsql
AS $$
DECLARE
    r RECORD;
BEGIN
    FOR r IN SELECT * FROM test2 ORDER BY x LOOP
        INSERT INTO test1 (a) VALUES (r.x);
        COMMIT;
    END LOOP;
END;
$$;

CALL transaction_test2();
</programlisting>
    Normally, cursors are automatically closed at transaction commit.
    However, a cursor created as part of a loop like this is automatically
    converted to a holdable cursor by the first <command>COMMIT</command> or
    <command>ROLLBACK</command>.  That means that the cursor is fully
    evaluated at the first <command>COMMIT</command> or
    <command>ROLLBACK</command> rather than row by row.  The cursor is still
    removed automatically after the loop, so this is mostly invisible to the
    user.
   </para>

   <para>
    Transaction commands are not allowed in cursor loops driven by commands
    that are not read-only (for example <command>UPDATE
    ... RETURNING</command>).
   </para>

   <para>
    A transaction cannot be ended inside a block with exception handlers.
   </para>
  </sect1>

  <sect1 id="plpgsql-errors-and-messages">
   <title>Errors and Messages</title>

  <sect2 id="plpgsql-statements-raise">
   <title>Reporting Errors and Messages</title>

   <indexterm>
    <primary>RAISE</primary>
    <secondary>in PL/pgSQL</secondary>
   </indexterm>

   <indexterm>
    <primary>reporting errors</primary>
    <secondary>in PL/pgSQL</secondary>
   </indexterm>

   <para>
    Use the <command>RAISE</command> statement to report messages and
    raise errors.

<synopsis>
RAISE <optional> <replaceable class="parameter">level</replaceable> </optional> '<replaceable class="parameter">format</replaceable>' <optional>, <replaceable class="parameter">expression</replaceable> <optional>, ... </optional></optional> <optional> USING <replaceable class="parameter">option</replaceable> = <replaceable class="parameter">expression</replaceable> <optional>, ... </optional> </optional>;
RAISE <optional> <replaceable class="parameter">level</replaceable> </optional> <replaceable class="parameter">condition_name</replaceable> <optional> USING <replaceable class="parameter">option</replaceable> = <replaceable class="parameter">expression</replaceable> <optional>, ... </optional> </optional>;
RAISE <optional> <replaceable class="parameter">level</replaceable> </optional> SQLSTATE '<replaceable class="parameter">sqlstate</replaceable>' <optional> USING <replaceable class="parameter">option</replaceable> = <replaceable class="parameter">expression</replaceable> <optional>, ... </optional> </optional>;
RAISE <optional> <replaceable class="parameter">level</replaceable> </optional> USING <replaceable class="parameter">option</replaceable> = <replaceable class="parameter">expression</replaceable> <optional>, ... </optional>;
RAISE ;
</synopsis>

    The <replaceable class="parameter">level</replaceable> option specifies
    the error severity.  Allowed levels are <literal>DEBUG</literal>,
    <literal>LOG</literal>, <literal>INFO</literal>,
    <literal>NOTICE</literal>, <literal>WARNING</literal>,
    and <literal>EXCEPTION</literal>, with <literal>EXCEPTION</literal>
    being the default.
    <literal>EXCEPTION</literal> raises an error (which normally aborts the
    current transaction); the other levels only generate messages of different
    priority levels.
    Whether messages of a particular priority are reported to the client,
    written to the server log, or both is controlled by the
    <xref linkend="guc-log-min-messages"/> and
    <xref linkend="guc-client-min-messages"/> configuration
    variables. See <xref linkend="runtime-config"/> for more
    information.
   </para>

   <para>
    After <replaceable class="parameter">level</replaceable> if any,
    you can specify a <replaceable class="parameter">format</replaceable> string
    (which must be a simple string literal, not an expression).  The
    format string specifies the error message text to be reported.
    The format string can be followed
    by optional argument expressions to be inserted into the message.
    Inside the format string, <literal>%</literal> is replaced by the
    string representation of the next optional argument's value. Write
    <literal>%%</literal> to emit a literal <literal>%</literal>.
    The number of arguments must match the number of <literal>%</literal>
    placeholders in the format string, or an error is raised during
    the compilation of the function.
   </para>

   <para>
    In this example, the value of <literal>v_job_id</literal> will replace the
    <literal>%</literal> in the string:
<programlisting>
RAISE NOTICE 'Calling cs_create_job(%)', v_job_id;
</programlisting>
   </para>

   <para>
    You can attach additional information to the error report by writing
    <literal>USING</literal> followed by <replaceable
    class="parameter">option</replaceable> = <replaceable
    class="parameter">expression</replaceable> items.  Each
    <replaceable class="parameter">expression</replaceable> can be any
    string-valued expression.  The allowed <replaceable
    class="parameter">option</replaceable> key words are:

    <variablelist id="raise-using-options">
     <varlistentry>
      <term><literal>MESSAGE</literal></term>
      <listitem>
       <para>Sets the error message text.  This option can't be used in the
        form of <command>RAISE</command> that includes a format string
        before <literal>USING</literal>.</para>
      </listitem>
     </varlistentry>

     <varlistentry>
      <term><literal>DETAIL</literal></term>
      <listitem>
       <para>Supplies an error detail message.</para>
      </listitem>
     </varlistentry>

     <varlistentry>
      <term><literal>HINT</literal></term>
      <listitem>
       <para>Supplies a hint message.</para>
      </listitem>
     </varlistentry>

     <varlistentry>
      <term><literal>ERRCODE</literal></term>
      <listitem>
       <para>Specifies the error code (SQLSTATE) to report, either by condition
        name, as shown in <xref linkend="errcodes-appendix"/>, or directly as a
        five-character SQLSTATE code.</para>
      </listitem>
     </varlistentry>

     <varlistentry>
      <term><literal>COLUMN</literal></term>
      <term><literal>CONSTRAINT</literal></term>
      <term><literal>DATATYPE</literal></term>
      <term><literal>TABLE</literal></term>
      <term><literal>SCHEMA</literal></term>
      <listitem>
       <para>Supplies the name of a related object.</para>
      </listitem>
     </varlistentry>
    </variablelist>
   </para>

   <para>
    This example will abort the transaction with the given error message
    and hint:
<programlisting>
RAISE EXCEPTION 'Nonexistent ID --> %', user_id
      USING HINT = 'Please check your user ID';
</programlisting>
   </para>

   <para>
    These two examples show equivalent ways of setting the SQLSTATE:
<programlisting>
RAISE 'Duplicate user ID: %', user_id USING ERRCODE = 'unique_violation';
RAISE 'Duplicate user ID: %', user_id USING ERRCODE = '23505';
</programlisting>
   </para>

   <para>
    There is a second <command>RAISE</command> syntax in which the main argument
    is the condition name or SQLSTATE to be reported, for example:
<programlisting>
RAISE division_by_zero;
RAISE SQLSTATE '22012';
</programlisting>
    In this syntax, <literal>USING</literal> can be used to supply a custom
    error message, detail, or hint.  Another way to do the earlier
    example is
<programlisting>
RAISE unique_violation USING MESSAGE = 'Duplicate user ID: ' || user_id;
</programlisting>
   </para>

   <para>
    Still another variant is to write <literal>RAISE USING</literal> or <literal>RAISE
    <replaceable class="parameter">level</replaceable> USING</literal> and put
    everything else into the <literal>USING</literal> list.
   </para>

   <para>
    The last variant of <command>RAISE</command> has no parameters at all.
    This form can only be used inside a <literal>BEGIN</literal> block's
    <literal>EXCEPTION</literal> clause;
    it causes the error currently being handled to be re-thrown.
   </para>

   <note>
    <para>
     Before <productname>PostgreSQL</productname> 9.1, <command>RAISE</command> without
     parameters was interpreted as re-throwing the error from the block
     containing the active exception handler.  Thus an <literal>EXCEPTION</literal>
     clause nested within that handler could not catch it, even if the
     <command>RAISE</command> was within the nested <literal>EXCEPTION</literal> clause's
     block. This was deemed surprising as well as being incompatible with
     Oracle's PL/SQL.
    </para>
   </note>

   <para>
    If no condition name nor SQLSTATE is specified in a
    <command>RAISE EXCEPTION</command> command, the default is to use
    <literal>raise_exception</literal> (<literal>P0001</literal>).
    If no message text is specified, the default is to use the condition
    name or SQLSTATE as message text.
   </para>

   <note>
    <para>
     When specifying an error code by SQLSTATE code, you are not
     limited to the predefined error codes, but can select any
     error code consisting of five digits and/or upper-case ASCII
     letters, other than <literal>00000</literal>.  It is recommended that
     you avoid throwing error codes that end in three zeroes, because
     these are category codes and can only be trapped by trapping
     the whole category.
    </para>
   </note>

  </sect2>

  <sect2 id="plpgsql-statements-assert">
   <title>Checking Assertions</title>

   <indexterm>
    <primary>ASSERT</primary>
    <secondary>in PL/pgSQL</secondary>
   </indexterm>

   <indexterm>
    <primary>assertions</primary>
    <secondary>in PL/pgSQL</secondary>
   </indexterm>

   <indexterm>
    <primary><varname>plpgsql.check_asserts</varname> configuration parameter</primary>
   </indexterm>

   <para>
    The <command>ASSERT</command> statement is a convenient shorthand for
    inserting debugging checks into <application>PL/pgSQL</application>
    functions.

<synopsis>
ASSERT <replaceable class="parameter">condition</replaceable> <optional> , <replaceable class="parameter">message</replaceable> </optional>;
</synopsis>

    The <replaceable class="parameter">condition</replaceable> is a Boolean
    expression that is expected to always evaluate to true; if it does,
    the <command>ASSERT</command> statement does nothing further.  If the
    result is false or null, then an <literal>ASSERT_FAILURE</literal> exception
    is raised.  (If an error occurs while evaluating
    the <replaceable class="parameter">condition</replaceable>, it is
    reported as a normal error.)
   </para>

   <para>
    If the optional <replaceable class="parameter">message</replaceable> is
    provided, it is an expression whose result (if not null) replaces the
    default error message text <quote>assertion failed</quote>, should
    the <replaceable class="parameter">condition</replaceable> fail.
    The <replaceable class="parameter">message</replaceable> expression is
    not evaluated in the normal case where the assertion succeeds.
   </para>

   <para>
    Testing of assertions can be enabled or disabled via the configuration
    parameter <literal>plpgsql.check_asserts</literal>, which takes a Boolean
    value; the default is <literal>on</literal>.  If this parameter
    is <literal>off</literal> then <command>ASSERT</command> statements do nothing.
   </para>

   <para>
    Note that <command>ASSERT</command> is meant for detecting program
    bugs, not for reporting ordinary error conditions.  Use
    the <command>RAISE</command> statement, described above, for that.
   </para>

  </sect2>

 </sect1>

 <sect1 id="plpgsql-trigger">
  <title>Trigger Functions</title>

  <indexterm zone="plpgsql-trigger">
   <primary>trigger</primary>
   <secondary>in PL/pgSQL</secondary>
  </indexterm>

  <para>
   <application>PL/pgSQL</application> can be used to define trigger
   functions on data changes or database events.
   A trigger function is created with the <command>CREATE FUNCTION</command>
   command, declaring it as a function with no arguments and a return type of
   <type>trigger</type> (for data change triggers) or
   <type>event_trigger</type> (for database event triggers).
   Special local variables named <varname>TG_<replaceable>something</replaceable></varname> are
   automatically defined to describe the condition that triggered the call.
  </para>

  <sect2 id="plpgsql-dml-trigger">
   <title>Triggers on Data Changes</title>

  <para>
   A <link linkend="triggers">data change trigger</link> is declared as a
   function with no arguments and a return type of <type>trigger</type>.
   Note that the function must be declared with no arguments even if it
   expects to receive some arguments specified in <command>CREATE TRIGGER</command>
   &mdash; such arguments are passed via <varname>TG_ARGV</varname>, as described
   below.
  </para>

  <para>
   When a <application>PL/pgSQL</application> function is called as a
   trigger, several special variables are created automatically in the
   top-level block. They are:

   <variablelist>
    <varlistentry>
     <term><varname>NEW</varname></term>
     <listitem>
      <para>
       Data type <type>RECORD</type>; variable holding the new
       database row for <command>INSERT</command>/<command>UPDATE</command> operations in row-level
       triggers. This variable is null in statement-level triggers
       and for <command>DELETE</command> operations.
      </para>
     </listitem>
    </varlistentry>

    <varlistentry>
     <term><varname>OLD</varname></term>
     <listitem>
      <para>
       Data type <type>RECORD</type>; variable holding the old
       database row for <command>UPDATE</command>/<command>DELETE</command> operations in row-level
       triggers. This variable is null in statement-level triggers
       and for <command>INSERT</command> operations.
      </para>
     </listitem>
    </varlistentry>

    <varlistentry>
     <term><varname>TG_NAME</varname></term>
     <listitem>
      <para>
       Data type <type>name</type>; variable that contains the name of the trigger actually
       fired.
      </para>
     </listitem>
    </varlistentry>

    <varlistentry>
     <term><varname>TG_WHEN</varname></term>
     <listitem>
      <para>
       Data type <type>text</type>; a string of
       <literal>BEFORE</literal>, <literal>AFTER</literal>, or
       <literal>INSTEAD OF</literal>, depending on the trigger's definition.
      </para>
     </listitem>
    </varlistentry>

    <varlistentry>
     <term><varname>TG_LEVEL</varname></term>
     <listitem>
      <para>
       Data type <type>text</type>; a string of either
       <literal>ROW</literal> or <literal>STATEMENT</literal>
       depending on the trigger's definition.
      </para>
     </listitem>
    </varlistentry>

    <varlistentry>
     <term><varname>TG_OP</varname></term>
     <listitem>
      <para>
       Data type <type>text</type>; a string of
       <literal>INSERT</literal>, <literal>UPDATE</literal>,
       <literal>DELETE</literal>, or <literal>TRUNCATE</literal>
       telling for which operation the trigger was fired.
      </para>
     </listitem>
    </varlistentry>

    <varlistentry>
     <term><varname>TG_RELID</varname></term>
     <listitem>
      <para>
       Data type <type>oid</type>; the object ID of the table that caused the
       trigger invocation.
      </para>
     </listitem>
    </varlistentry>

    <varlistentry>
     <term><varname>TG_RELNAME</varname></term>
     <listitem>
      <para>
       Data type <type>name</type>; the name of the table that caused the trigger
       invocation. This is now deprecated, and could disappear in a future
       release. Use <literal>TG_TABLE_NAME</literal> instead.
      </para>
     </listitem>
    </varlistentry>

    <varlistentry>
     <term><varname>TG_TABLE_NAME</varname></term>
     <listitem>
      <para>
       Data type <type>name</type>; the name of the table that
       caused the trigger invocation.
      </para>
     </listitem>
    </varlistentry>

    <varlistentry>
     <term><varname>TG_TABLE_SCHEMA</varname></term>
     <listitem>
      <para>
       Data type <type>name</type>; the name of the schema of the
       table that caused the trigger invocation.
      </para>
     </listitem>
    </varlistentry>

    <varlistentry>
     <term><varname>TG_NARGS</varname></term>
     <listitem>
      <para>
       Data type <type>integer</type>; the number of arguments given to the trigger
       function in the <command>CREATE TRIGGER</command> statement.
      </para>
     </listitem>
    </varlistentry>

    <varlistentry>
     <term><varname>TG_ARGV[]</varname></term>
     <listitem>
      <para>
       Data type array of <type>text</type>; the arguments from
       the <command>CREATE TRIGGER</command> statement.
       The index counts from 0. Invalid
       indexes (less than 0 or greater than or equal to <varname>tg_nargs</varname>)
       result in a null value.
      </para>
     </listitem>
    </varlistentry>
   </variablelist>
  </para>

   <para>
    A trigger function must return either <symbol>NULL</symbol> or a
    record/row value having exactly the structure of the table the
    trigger was fired for.
   </para>

   <para>
    Row-level triggers fired <literal>BEFORE</literal> can return null to signal the
    trigger manager to skip the rest of the operation for this row
    (i.e., subsequent triggers are not fired, and the
    <command>INSERT</command>/<command>UPDATE</command>/<command>DELETE</command> does not occur
    for this row).  If a nonnull
    value is returned then the operation proceeds with that row value.
    Returning a row value different from the original value
    of <varname>NEW</varname> alters the row that will be inserted or
    updated.  Thus, if the trigger function wants the triggering
    action to succeed normally without altering the row
    value, <varname>NEW</varname> (or a value equal thereto) has to be
    returned.  To alter the row to be stored, it is possible to
    replace single values directly in <varname>NEW</varname> and return the
    modified <varname>NEW</varname>, or to build a complete new record/row to
    return.  In the case of a before-trigger
    on <command>DELETE</command>, the returned value has no direct
    effect, but it has to be nonnull to allow the trigger action to
    proceed.  Note that <varname>NEW</varname> is null
    in <command>DELETE</command> triggers, so returning that is
    usually not sensible.  The usual idiom in <command>DELETE</command>
    triggers is to return <varname>OLD</varname>.
   </para>

   <para>
    <literal>INSTEAD OF</literal> triggers (which are always row-level triggers,
    and may only be used on views) can return null to signal that they did
    not perform any updates, and that the rest of the operation for this
    row should be skipped (i.e., subsequent triggers are not fired, and the
    row is not counted in the rows-affected status for the surrounding
    <command>INSERT</command>/<command>UPDATE</command>/<command>DELETE</command>).
    Otherwise a nonnull value should be returned, to signal
    that the trigger performed the requested operation. For
    <command>INSERT</command> and <command>UPDATE</command> operations, the return value
    should be <varname>NEW</varname>, which the trigger function may modify to
    support <command>INSERT RETURNING</command> and <command>UPDATE RETURNING</command>
    (this will also affect the row value passed to any subsequent triggers,
    or passed to a special <varname>EXCLUDED</varname> alias reference within
    an <command>INSERT</command> statement with an <literal>ON CONFLICT DO
    UPDATE</literal> clause).  For <command>DELETE</command> operations, the return
    value should be <varname>OLD</varname>.
   </para>

   <para>
    The return value of a row-level trigger
    fired <literal>AFTER</literal> or a statement-level trigger
    fired <literal>BEFORE</literal> or <literal>AFTER</literal> is
    always ignored; it might as well be null. However, any of these types of
    triggers might still abort the entire operation by raising an error.
   </para>

   <para>
    <xref linkend="plpgsql-trigger-example"/> shows an example of a
    trigger function in <application>PL/pgSQL</application>.
   </para>

   <example id="plpgsql-trigger-example">
    <title>A <application>PL/pgSQL</application> Trigger Function</title>

    <para>
     This example trigger ensures that any time a row is inserted or updated
     in the table, the current user name and time are stamped into the
     row. And it checks that an employee's name is given and that the
     salary is a positive value.
    </para>

<programlisting>
CREATE TABLE emp (
    empname text,
    salary integer,
    last_date timestamp,
    last_user text
);

CREATE FUNCTION emp_stamp() RETURNS trigger AS $emp_stamp$
    BEGIN
        -- Check that empname and salary are given
        IF NEW.empname IS NULL THEN
            RAISE EXCEPTION 'empname cannot be null';
        END IF;
        IF NEW.salary IS NULL THEN
            RAISE EXCEPTION '% cannot have null salary', NEW.empname;
        END IF;

        -- Who works for us when they must pay for it?
        IF NEW.salary &lt; 0 THEN
            RAISE EXCEPTION '% cannot have a negative salary', NEW.empname;
        END IF;

        -- Remember who changed the payroll when
        NEW.last_date := current_timestamp;
        NEW.last_user := current_user;
        RETURN NEW;
    END;
$emp_stamp$ LANGUAGE plpgsql;

CREATE TRIGGER emp_stamp BEFORE INSERT OR UPDATE ON emp
    FOR EACH ROW EXECUTE FUNCTION emp_stamp();
</programlisting>
   </example>

   <para>
    Another way to log changes to a table involves creating a new table that
    holds a row for each insert, update, or delete that occurs. This approach
    can be thought of as auditing changes to a table.
    <xref linkend="plpgsql-trigger-audit-example"/> shows an example of an
    audit trigger function in <application>PL/pgSQL</application>.
   </para>

   <example id="plpgsql-trigger-audit-example">
    <title>A <application>PL/pgSQL</application> Trigger Function for Auditing</title>

    <para>
     This example trigger ensures that any insert, update or delete of a row
     in the <literal>emp</literal> table is recorded (i.e., audited) in the <literal>emp_audit</literal> table.
     The current time and user name are stamped into the row, together with
     the type of operation performed on it.
    </para>

<programlisting>
CREATE TABLE emp (
    empname           text NOT NULL,
    salary            integer
);

CREATE TABLE emp_audit(
    operation         char(1)   NOT NULL,
    stamp             timestamp NOT NULL,
    userid            text      NOT NULL,
    empname           text      NOT NULL,
    salary integer
);

CREATE OR REPLACE FUNCTION process_emp_audit() RETURNS TRIGGER AS $emp_audit$
    BEGIN
        --
        -- Create a row in emp_audit to reflect the operation performed on emp,
        -- making use of the special variable TG_OP to work out the operation.
        --
        IF (TG_OP = 'DELETE') THEN
            INSERT INTO emp_audit SELECT 'D', now(), current_user, OLD.*;
        ELSIF (TG_OP = 'UPDATE') THEN
            INSERT INTO emp_audit SELECT 'U', now(), current_user, NEW.*;
        ELSIF (TG_OP = 'INSERT') THEN
            INSERT INTO emp_audit SELECT 'I', now(), current_user, NEW.*;
        END IF;
        RETURN NULL; -- result is ignored since this is an AFTER trigger
    END;
$emp_audit$ LANGUAGE plpgsql;

CREATE TRIGGER emp_audit
AFTER INSERT OR UPDATE OR DELETE ON emp
    FOR EACH ROW EXECUTE FUNCTION process_emp_audit();
</programlisting>
   </example>

   <para>
    A variation of the previous example uses a view joining the main table
    to the audit table, to show when each entry was last modified. This
    approach still records the full audit trail of changes to the table,
    but also presents a simplified view of the audit trail, showing just
    the last modified timestamp derived from the audit trail for each entry.
    <xref linkend="plpgsql-view-trigger-audit-example"/> shows an example
    of an audit trigger on a view in <application>PL/pgSQL</application>.
   </para>

   <example id="plpgsql-view-trigger-audit-example">
    <title>A <application>PL/pgSQL</application> View Trigger Function for Auditing</title>

    <para>
     This example uses a trigger on the view to make it updatable, and
     ensure that any insert, update or delete of a row in the view is
     recorded (i.e., audited) in the <literal>emp_audit</literal> table. The current time
     and user name are recorded, together with the type of operation
     performed, and the view displays the last modified time of each row.
    </para>

<programlisting>
CREATE TABLE emp (
    empname           text PRIMARY KEY,
    salary            integer
);

CREATE TABLE emp_audit(
    operation         char(1)   NOT NULL,
    userid            text      NOT NULL,
    empname           text      NOT NULL,
    salary            integer,
    stamp             timestamp NOT NULL
);

CREATE VIEW emp_view AS
    SELECT e.empname,
           e.salary,
           max(ea.stamp) AS last_updated
      FROM emp e
      LEFT JOIN emp_audit ea ON ea.empname = e.empname
     GROUP BY 1, 2;

CREATE OR REPLACE FUNCTION update_emp_view() RETURNS TRIGGER AS $$
    BEGIN
        --
        -- Perform the required operation on emp, and create a row in emp_audit
        -- to reflect the change made to emp.
        --
        IF (TG_OP = 'DELETE') THEN
            DELETE FROM emp WHERE empname = OLD.empname;
            IF NOT FOUND THEN RETURN NULL; END IF;

            OLD.last_updated = now();
            INSERT INTO emp_audit VALUES('D', current_user, OLD.*);
            RETURN OLD;
        ELSIF (TG_OP = 'UPDATE') THEN
            UPDATE emp SET salary = NEW.salary WHERE empname = OLD.empname;
            IF NOT FOUND THEN RETURN NULL; END IF;

            NEW.last_updated = now();
            INSERT INTO emp_audit VALUES('U', current_user, NEW.*);
            RETURN NEW;
        ELSIF (TG_OP = 'INSERT') THEN
            INSERT INTO emp VALUES(NEW.empname, NEW.salary);

            NEW.last_updated = now();
            INSERT INTO emp_audit VALUES('I', current_user, NEW.*);
            RETURN NEW;
        END IF;
    END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER emp_audit
INSTEAD OF INSERT OR UPDATE OR DELETE ON emp_view
    FOR EACH ROW EXECUTE FUNCTION update_emp_view();
</programlisting>
   </example>

   <para>
    One use of triggers is to maintain a summary table
    of another table. The resulting summary can be used in place of the
    original table for certain queries &mdash; often with vastly reduced run
    times.
    This technique is commonly used in Data Warehousing, where the tables
    of measured or observed data (called fact tables) might be extremely large.
    <xref linkend="plpgsql-trigger-summary-example"/> shows an example of a
    trigger function in <application>PL/pgSQL</application> that maintains
    a summary table for a fact table in a data warehouse.
   </para>


   <example id="plpgsql-trigger-summary-example">
    <title>A <application>PL/pgSQL</application> Trigger Function for Maintaining a Summary Table</title>

    <para>
     The schema detailed here is partly based on the <emphasis>Grocery Store
     </emphasis> example from <emphasis>The Data Warehouse Toolkit</emphasis>
     by Ralph Kimball.
    </para>

<programlisting>
--
-- Main tables - time dimension and sales fact.
--
CREATE TABLE time_dimension (
    time_key                    integer NOT NULL,
    day_of_week                 integer NOT NULL,
    day_of_month                integer NOT NULL,
    month                       integer NOT NULL,
    quarter                     integer NOT NULL,
    year                        integer NOT NULL
);
CREATE UNIQUE INDEX time_dimension_key ON time_dimension(time_key);

CREATE TABLE sales_fact (
    time_key                    integer NOT NULL,
    product_key                 integer NOT NULL,
    store_key                   integer NOT NULL,
    amount_sold                 numeric(12,2) NOT NULL,
    units_sold                  integer NOT NULL,
    amount_cost                 numeric(12,2) NOT NULL
);
CREATE INDEX sales_fact_time ON sales_fact(time_key);

--
-- Summary table - sales by time.
--
CREATE TABLE sales_summary_bytime (
    time_key                    integer NOT NULL,
    amount_sold                 numeric(15,2) NOT NULL,
    units_sold                  numeric(12) NOT NULL,
    amount_cost                 numeric(15,2) NOT NULL
);
CREATE UNIQUE INDEX sales_summary_bytime_key ON sales_summary_bytime(time_key);

--
-- Function and trigger to amend summarized column(s) on UPDATE, INSERT, DELETE.
--
CREATE OR REPLACE FUNCTION maint_sales_summary_bytime() RETURNS TRIGGER
AS $maint_sales_summary_bytime$
    DECLARE
        delta_time_key          integer;
        delta_amount_sold       numeric(15,2);
        delta_units_sold        numeric(12);
        delta_amount_cost       numeric(15,2);
    BEGIN

        -- Work out the increment/decrement amount(s).
        IF (TG_OP = 'DELETE') THEN

            delta_time_key = OLD.time_key;
            delta_amount_sold = -1 * OLD.amount_sold;
            delta_units_sold = -1 * OLD.units_sold;
            delta_amount_cost = -1 * OLD.amount_cost;

        ELSIF (TG_OP = 'UPDATE') THEN

            -- forbid updates that change the time_key -
            -- (probably not too onerous, as DELETE + INSERT is how most
            -- changes will be made).
            IF ( OLD.time_key != NEW.time_key) THEN
                RAISE EXCEPTION 'Update of time_key : % -&gt; % not allowed',
                                                      OLD.time_key, NEW.time_key;
            END IF;

            delta_time_key = OLD.time_key;
            delta_amount_sold = NEW.amount_sold - OLD.amount_sold;
            delta_units_sold = NEW.units_sold - OLD.units_sold;
            delta_amount_cost = NEW.amount_cost - OLD.amount_cost;

        ELSIF (TG_OP = 'INSERT') THEN

            delta_time_key = NEW.time_key;
            delta_amount_sold = NEW.amount_sold;
            delta_units_sold = NEW.units_sold;
            delta_amount_cost = NEW.amount_cost;

        END IF;


        -- Insert or update the summary row with the new values.
        &lt;&lt;insert_update&gt;&gt;
        LOOP
            UPDATE sales_summary_bytime
                SET amount_sold = amount_sold + delta_amount_sold,
                    units_sold = units_sold + delta_units_sold,
                    amount_cost = amount_cost + delta_amount_cost
                WHERE time_key = delta_time_key;

            EXIT insert_update WHEN found;

            BEGIN
                INSERT INTO sales_summary_bytime (
                            time_key,
                            amount_sold,
                            units_sold,
                            amount_cost)
                    VALUES (
                            delta_time_key,
                            delta_amount_sold,
                            delta_units_sold,
                            delta_amount_cost
                           );

                EXIT insert_update;

            EXCEPTION
                WHEN UNIQUE_VIOLATION THEN
                    -- do nothing
            END;
        END LOOP insert_update;

        RETURN NULL;

    END;
$maint_sales_summary_bytime$ LANGUAGE plpgsql;

CREATE TRIGGER maint_sales_summary_bytime
AFTER INSERT OR UPDATE OR DELETE ON sales_fact
    FOR EACH ROW EXECUTE FUNCTION maint_sales_summary_bytime();

INSERT INTO sales_fact VALUES(1,1,1,10,3,15);
INSERT INTO sales_fact VALUES(1,2,1,20,5,35);
INSERT INTO sales_fact VALUES(2,2,1,40,15,135);
INSERT INTO sales_fact VALUES(2,3,1,10,1,13);
SELECT * FROM sales_summary_bytime;
DELETE FROM sales_fact WHERE product_key = 1;
SELECT * FROM sales_summary_bytime;
UPDATE sales_fact SET units_sold = units_sold * 2;
SELECT * FROM sales_summary_bytime;
</programlisting>
   </example>

   <para>
    <literal>AFTER</literal> triggers can also make use of <firstterm>transition
    tables</firstterm> to inspect the entire set of rows changed by the triggering
    statement.  The <command>CREATE TRIGGER</command> command assigns names to one
    or both transition tables, and then the function can refer to those names
    as though they were read-only temporary tables.
    <xref linkend="plpgsql-trigger-audit-transition-example"/> shows an example.
   </para>

   <example id="plpgsql-trigger-audit-transition-example">
    <title>Auditing with Transition Tables</title>

    <para>
     This example produces the same results as
     <xref linkend="plpgsql-trigger-audit-example"/>, but instead of using a
     trigger that fires for every row, it uses a trigger that fires once
     per statement, after collecting the relevant information in a transition
     table.  This can be significantly faster than the row-trigger approach
     when the invoking statement has modified many rows.  Notice that we must
     make a separate trigger declaration for each kind of event, since the
     <literal>REFERENCING</literal> clauses must be different for each case.  But
     this does not stop us from using a single trigger function if we choose.
     (In practice, it might be better to use three separate functions and
     avoid the run-time tests on <varname>TG_OP</varname>.)
    </para>

<programlisting>
CREATE TABLE emp (
    empname           text NOT NULL,
    salary            integer
);

CREATE TABLE emp_audit(
    operation         char(1)   NOT NULL,
    stamp             timestamp NOT NULL,
    userid            text      NOT NULL,
    empname           text      NOT NULL,
    salary integer
);

CREATE OR REPLACE FUNCTION process_emp_audit() RETURNS TRIGGER AS $emp_audit$
    BEGIN
        --
        -- Create rows in emp_audit to reflect the operations performed on emp,
        -- making use of the special variable TG_OP to work out the operation.
        --
        IF (TG_OP = 'DELETE') THEN
            INSERT INTO emp_audit
                SELECT 'D', now(), current_user, o.* FROM old_table o;
        ELSIF (TG_OP = 'UPDATE') THEN
            INSERT INTO emp_audit
                SELECT 'U', now(), current_user, n.* FROM new_table n;
        ELSIF (TG_OP = 'INSERT') THEN
            INSERT INTO emp_audit
                SELECT 'I', now(), current_user, n.* FROM new_table n;
        END IF;
        RETURN NULL; -- result is ignored since this is an AFTER trigger
    END;
$emp_audit$ LANGUAGE plpgsql;

CREATE TRIGGER emp_audit_ins
    AFTER INSERT ON emp
    REFERENCING NEW TABLE AS new_table
    FOR EACH STATEMENT EXECUTE FUNCTION process_emp_audit();
CREATE TRIGGER emp_audit_upd
    AFTER UPDATE ON emp
    REFERENCING OLD TABLE AS old_table NEW TABLE AS new_table
    FOR EACH STATEMENT EXECUTE FUNCTION process_emp_audit();
CREATE TRIGGER emp_audit_del
    AFTER DELETE ON emp
    REFERENCING OLD TABLE AS old_table
    FOR EACH STATEMENT EXECUTE FUNCTION process_emp_audit();
</programlisting>
   </example>

</sect2>

  <sect2 id="plpgsql-event-trigger">
   <title>Triggers on Events</title>

   <para>
    <application>PL/pgSQL</application> can be used to define
    <link linkend="event-triggers">event triggers</link>.
    <productname>PostgreSQL</productname> requires that a function that
    is to be called as an event trigger must be declared as a function with
    no arguments and a return type of <literal>event_trigger</literal>.
   </para>

   <para>
    When a <application>PL/pgSQL</application> function is called as an
    event trigger, several special variables are created automatically
    in the top-level block. They are:

   <variablelist>
    <varlistentry>
     <term><varname>TG_EVENT</varname></term>
     <listitem>
      <para>
       Data type <type>text</type>; a string representing the event the
       trigger is fired for.
      </para>
     </listitem>
    </varlistentry>

    <varlistentry>
     <term><varname>TG_TAG</varname></term>
     <listitem>
      <para>
       Data type <type>text</type>; variable that contains the command tag
       for which the trigger is fired.
      </para>
     </listitem>
    </varlistentry>
   </variablelist>
  </para>

   <para>
    <xref linkend="plpgsql-event-trigger-example"/> shows an example of an
    event trigger function in <application>PL/pgSQL</application>.
   </para>

   <example id="plpgsql-event-trigger-example">
    <title>A <application>PL/pgSQL</application> Event Trigger Function</title>

    <para>
     This example trigger simply raises a <literal>NOTICE</literal> message
     each time a supported command is executed.
    </para>

<programlisting>
CREATE OR REPLACE FUNCTION snitch() RETURNS event_trigger AS $$
BEGIN
    RAISE NOTICE 'snitch: % %', tg_event, tg_tag;
END;
$$ LANGUAGE plpgsql;

CREATE EVENT TRIGGER snitch ON ddl_command_start EXECUTE FUNCTION snitch();
</programlisting>
   </example>
  </sect2>

  </sect1>

  <sect1 id="plpgsql-implementation">
   <title><application>PL/pgSQL</application> under the Hood</title>

   <para>
    This section discusses some implementation details that are
    frequently important for <application>PL/pgSQL</application> users to know.
   </para>

  <sect2 id="plpgsql-var-subst">
   <title>Variable Substitution</title>

   <para>
    SQL statements and expressions within a <application>PL/pgSQL</application> function
    can refer to variables and parameters of the function.  Behind the scenes,
    <application>PL/pgSQL</application> substitutes query parameters for such references.
    Query parameters will only be substituted in places where they are
    syntactically permissible.  As an extreme case, consider
    this example of poor programming style:
<programlisting>
INSERT INTO foo (foo) VALUES (foo(foo));
</programlisting>
    The first occurrence of <literal>foo</literal> must syntactically be a table
    name, so it will not be substituted, even if the function has a variable
    named <literal>foo</literal>.  The second occurrence must be the name of a
    column of that table, so it will not be substituted either.  Likewise
    the third occurrence must be a function name, so it also will not be
    substituted for.  Only the last occurrence is a candidate to be a
    reference to a variable of the <application>PL/pgSQL</application>
    function.
   </para>

   <para>
    Another way to understand this is that variable substitution can only
    insert data values into an SQL command; it cannot dynamically change which
    database objects are referenced by the command.  (If you want to do
    that, you must build a command string dynamically, as explained in
    <xref linkend="plpgsql-statements-executing-dyn"/>.)
   </para>

   <para>
    Since the names of variables are syntactically no different from the names
    of table columns, there can be ambiguity in statements that also refer to
    tables: is a given name meant to refer to a table column, or a variable?
    Let's change the previous example to
<programlisting>
INSERT INTO dest (col) SELECT foo + bar FROM src;
</programlisting>
    Here, <literal>dest</literal> and <literal>src</literal> must be table names, and
    <literal>col</literal> must be a column of <literal>dest</literal>, but <literal>foo</literal>
    and <literal>bar</literal> might reasonably be either variables of the function
    or columns of <literal>src</literal>.
   </para>

   <para>
    By default, <application>PL/pgSQL</application> will report an error if a name
    in an SQL statement could refer to either a variable or a table column.
    You can fix such a problem by renaming the variable or column,
    or by qualifying the ambiguous reference, or by telling
    <application>PL/pgSQL</application> which interpretation to prefer.
   </para>

   <para>
    The simplest solution is to rename the variable or column.
    A common coding rule is to use a
    different naming convention for <application>PL/pgSQL</application>
    variables than you use for column names.  For example,
    if you consistently name function variables
    <literal>v_<replaceable>something</replaceable></literal> while none of your
    column names start with <literal>v_</literal>, no conflicts will occur.
   </para>

   <para>
    Alternatively you can qualify ambiguous references to make them clear.
    In the above example, <literal>src.foo</literal> would be an unambiguous reference
    to the table column.  To create an unambiguous reference to a variable,
    declare it in a labeled block and use the block's label
    (see <xref linkend="plpgsql-structure"/>).  For example,
<programlisting>
&lt;&lt;block&gt;&gt;
DECLARE
    foo int;
BEGIN
    foo := ...;
    INSERT INTO dest (col) SELECT block.foo + bar FROM src;
</programlisting>
    Here <literal>block.foo</literal> means the variable even if there is a column
    <literal>foo</literal> in <literal>src</literal>.  Function parameters, as well as
    special variables such as <literal>FOUND</literal>, can be qualified by the
    function's name, because they are implicitly declared in an outer block
    labeled with the function's name.
   </para>

   <para>
    Sometimes it is impractical to fix all the ambiguous references in a
    large body of <application>PL/pgSQL</application> code.  In such cases you can
    specify that <application>PL/pgSQL</application> should resolve ambiguous references
    as the variable (which is compatible with <application>PL/pgSQL</application>'s
    behavior before <productname>PostgreSQL</productname> 9.0), or as the
    table column (which is compatible with some other systems such as
    <productname>Oracle</productname>).
   </para>

   <indexterm>
     <primary><varname>plpgsql.variable_conflict</varname> configuration parameter</primary>
   </indexterm>

   <para>
    To change this behavior on a system-wide basis, set the configuration
    parameter <literal>plpgsql.variable_conflict</literal> to one of
    <literal>error</literal>, <literal>use_variable</literal>, or
    <literal>use_column</literal> (where <literal>error</literal> is the factory default).
    This parameter affects subsequent compilations
    of statements in <application>PL/pgSQL</application> functions, but not statements
    already compiled in the current session.
    Because changing this setting
    can cause unexpected changes in the behavior of <application>PL/pgSQL</application>
    functions, it can only be changed by a superuser.
   </para>

   <para>
    You can also set the behavior on a function-by-function basis, by
    inserting one of these special commands at the start of the function
    text:
<programlisting>
#variable_conflict error
#variable_conflict use_variable
#variable_conflict use_column
</programlisting>
    These commands affect only the function they are written in, and override
    the setting of <literal>plpgsql.variable_conflict</literal>.  An example is
<programlisting>
CREATE FUNCTION stamp_user(id int, comment text) RETURNS void AS $$
    #variable_conflict use_variable
    DECLARE
        curtime timestamp := now();
    BEGIN
        UPDATE users SET last_modified = curtime, comment = comment
          WHERE users.id = id;
    END;
$$ LANGUAGE plpgsql;
</programlisting>
    In the <literal>UPDATE</literal> command, <literal>curtime</literal>, <literal>comment</literal>,
    and <literal>id</literal> will refer to the function's variable and parameters
    whether or not <literal>users</literal> has columns of those names.  Notice
    that we had to qualify the reference to <literal>users.id</literal> in the
    <literal>WHERE</literal> clause to make it refer to the table column.
    But we did not have to qualify the reference to <literal>comment</literal>
    as a target in the <literal>UPDATE</literal> list, because syntactically
    that must be a column of <literal>users</literal>.  We could write the same
    function without depending on the <literal>variable_conflict</literal> setting
    in this way:
<programlisting>
CREATE FUNCTION stamp_user(id int, comment text) RETURNS void AS $$
    &lt;&lt;fn&gt;&gt;
    DECLARE
        curtime timestamp := now();
    BEGIN
        UPDATE users SET last_modified = fn.curtime, comment = stamp_user.comment
          WHERE users.id = stamp_user.id;
    END;
$$ LANGUAGE plpgsql;
</programlisting>
   </para>

   <para>
    Variable substitution does not happen in a command string given
    to <command>EXECUTE</command> or one of its variants.  If you need to
    insert a varying value into such a command, do so as part of
    constructing the string value, or use <literal>USING</literal>, as illustrated in
    <xref linkend="plpgsql-statements-executing-dyn"/>.
   </para>

   <para>
    Variable substitution currently works only in <command>SELECT</command>,
    <command>INSERT</command>, <command>UPDATE</command>,
    <command>DELETE</command>, and commands containing one of
    these (such as <command>EXPLAIN</command> and <command>CREATE TABLE
    ... AS SELECT</command>),
    because the main SQL engine allows query parameters only in these
    commands.  To use a non-constant name or value in other statement
    types (generically called utility statements), you must construct
    the utility statement as a string and <command>EXECUTE</command> it.
   </para>

  </sect2>

  <sect2 id="plpgsql-plan-caching">
   <title>Plan Caching</title>

   <para>
    The <application>PL/pgSQL</application> interpreter parses the function's source
    text and produces an internal binary instruction tree the first time the
    function is called (within each session).  The instruction tree
    fully translates the
    <application>PL/pgSQL</application> statement structure, but individual
    <acronym>SQL</acronym> expressions and <acronym>SQL</acronym> commands
    used in the function are not translated immediately.
   </para>

   <para>
    <indexterm>
     <primary>preparing a query</primary>
     <secondary>in PL/pgSQL</secondary>
    </indexterm>
    As each expression and <acronym>SQL</acronym> command is first
    executed in the function, the <application>PL/pgSQL</application> interpreter
    parses and analyzes the command to create a prepared statement,
    using the <acronym>SPI</acronym> manager's
    <function>SPI_prepare</function> function.
    Subsequent visits to that expression or command
    reuse the prepared statement.  Thus, a function with conditional code
    paths that are seldom visited will never incur the overhead of
    analyzing those commands that are never executed within the current
    session.  A disadvantage is that errors
    in a specific expression or command cannot be detected until that
    part of the function is reached in execution.  (Trivial syntax
    errors will be detected during the initial parsing pass, but
    anything deeper will not be detected until execution.)
   </para>

   <para>
    <application>PL/pgSQL</application> (or more precisely, the SPI manager) can
    furthermore attempt to cache the execution plan associated with any
    particular prepared statement.  If a cached plan is not used, then
    a fresh execution plan is generated on each visit to the statement,
    and the current parameter values (that is, <application>PL/pgSQL</application>
    variable values) can be used to optimize the selected plan.  If the
    statement has no parameters, or is executed many times, the SPI manager
    will consider creating a <firstterm>generic</firstterm> plan that is not dependent
    on specific parameter values, and caching that for re-use.  Typically
    this will happen only if the execution plan is not very sensitive to
    the values of the <application>PL/pgSQL</application> variables referenced in it.
    If it is, generating a plan each time is a net win.  See <xref
    linkend="sql-prepare"/> for more information about the behavior of
    prepared statements.
   </para>

   <para>
    Because <application>PL/pgSQL</application> saves prepared statements
    and sometimes execution plans in this way,
    SQL commands that appear directly in a
    <application>PL/pgSQL</application> function must refer to the
    same tables and columns on every execution; that is, you cannot use
    a parameter as the name of a table or column in an SQL command.  To get
    around this restriction, you can construct dynamic commands using
    the <application>PL/pgSQL</application> <command>EXECUTE</command>
    statement &mdash; at the price of performing new parse analysis and
    constructing a new execution plan on every execution.
   </para>

    <para>
     The mutable nature of record variables presents another problem in this
     connection.  When fields of a record variable are used in
     expressions or statements, the data types of the fields must not
     change from one call of the function to the next, since each
     expression will be analyzed using the data type that is present
     when the expression is first reached.  <command>EXECUTE</command> can be
     used to get around this problem when necessary.
    </para>

    <para>
     If the same function is used as a trigger for more than one table,
     <application>PL/pgSQL</application> prepares and caches statements
     independently for each such table &mdash; that is, there is a cache
     for each trigger function and table combination, not just for each
     function.  This alleviates some of the problems with varying
     data types; for instance, a trigger function will be able to work
     successfully with a column named <literal>key</literal> even if it happens
     to have different types in different tables.
    </para>

    <para>
     Likewise, functions having polymorphic argument types have a separate
     statement cache for each combination of actual argument types they have
     been invoked for, so that data type differences do not cause unexpected
     failures.
    </para>

   <para>
    Statement caching can sometimes have surprising effects on the
    interpretation of time-sensitive values.  For example there
    is a difference between what these two functions do:

<programlisting>
CREATE FUNCTION logfunc1(logtxt text) RETURNS void AS $$
    BEGIN
        INSERT INTO logtable VALUES (logtxt, 'now');
    END;
$$ LANGUAGE plpgsql;
</programlisting>

     and:

<programlisting>
CREATE FUNCTION logfunc2(logtxt text) RETURNS void AS $$
    DECLARE
        curtime timestamp;
    BEGIN
        curtime := 'now';
        INSERT INTO logtable VALUES (logtxt, curtime);
    END;
$$ LANGUAGE plpgsql;
</programlisting>
    </para>

    <para>
     In the case of <function>logfunc1</function>, the
     <productname>PostgreSQL</productname> main parser knows when
     analyzing the <command>INSERT</command> that the
     string <literal>'now'</literal> should be interpreted as
     <type>timestamp</type>, because the target column of
     <classname>logtable</classname> is of that type. Thus,
     <literal>'now'</literal> will be converted to a <type>timestamp</type>
     constant when the
     <command>INSERT</command> is analyzed, and then used in all
     invocations of <function>logfunc1</function> during the lifetime
     of the session. Needless to say, this isn't what the programmer
     wanted.  A better idea is to use the <literal>now()</literal> or
     <literal>current_timestamp</literal> function.
    </para>

    <para>
     In the case of <function>logfunc2</function>, the
     <productname>PostgreSQL</productname> main parser does not know
     what type <literal>'now'</literal> should become and therefore
     it returns a data value of type <type>text</type> containing the string
     <literal>now</literal>. During the ensuing assignment
     to the local variable <varname>curtime</varname>, the
     <application>PL/pgSQL</application> interpreter casts this
     string to the <type>timestamp</type> type by calling the
     <function>textout</function> and <function>timestamp_in</function>
     functions for the conversion.  So, the computed time stamp is updated
     on each execution as the programmer expects.  Even though this
     happens to work as expected, it's not terribly efficient, so
     use of the <literal>now()</literal> function would still be a better idea.
    </para>

  </sect2>

  </sect1>

 <sect1 id="plpgsql-development-tips">
  <title>Tips for Developing in <application>PL/pgSQL</application></title>

   <para>
    One good way to develop in
    <application>PL/pgSQL</application> is to use the text editor of your
    choice to create your functions, and in another window, use
    <application>psql</application> to load and test those functions.
    If you are doing it this way, it
    is a good idea to write the function using <command>CREATE OR
    REPLACE FUNCTION</command>. That way you can just reload the file to update
    the function definition.  For example:
<programlisting>
CREATE OR REPLACE FUNCTION testfunc(integer) RETURNS integer AS $$
          ....
$$ LANGUAGE plpgsql;
</programlisting>
   </para>

   <para>
    While running <application>psql</application>, you can load or reload such
    a function definition file with:
<programlisting>
\i filename.sql
</programlisting>
    and then immediately issue SQL commands to test the function.
   </para>

   <para>
    Another good way to develop in <application>PL/pgSQL</application> is with a
    GUI database access tool that facilitates development in a
    procedural language. One example of such a tool is
    <application>pgAdmin</application>, although others exist. These tools often
    provide convenient features such as escaping single quotes and
    making it easier to recreate and debug functions.
   </para>

  <sect2 id="plpgsql-quote-tips">
   <title>Handling of Quotation Marks</title>

   <para>
    The code of a <application>PL/pgSQL</application> function is specified in
    <command>CREATE FUNCTION</command> as a string literal.  If you
    write the string literal in the ordinary way with surrounding
    single quotes, then any single quotes inside the function body
    must be doubled; likewise any backslashes must be doubled (assuming
    escape string syntax is used).
    Doubling quotes is at best tedious, and in more complicated cases
    the code can become downright incomprehensible, because you can
    easily find yourself needing half a dozen or more adjacent quote marks.
    It's recommended that you instead write the function body as a
    <quote>dollar-quoted</quote> string literal (see <xref
    linkend="sql-syntax-dollar-quoting"/>).  In the dollar-quoting
    approach, you never double any quote marks, but instead take care to
    choose a different dollar-quoting delimiter for each level of
    nesting you need.  For example, you might write the <command>CREATE
    FUNCTION</command> command as:
<programlisting>
CREATE OR REPLACE FUNCTION testfunc(integer) RETURNS integer AS $PROC$
          ....
$PROC$ LANGUAGE plpgsql;
</programlisting>
    Within this, you might use quote marks for simple literal strings in
    SQL commands and <literal>$$</literal> to delimit fragments of SQL commands
    that you are assembling as strings.  If you need to quote text that
    includes <literal>$$</literal>, you could use <literal>$Q$</literal>, and so on.
   </para>

   <para>
    The following chart shows what you have to do when writing quote
    marks without dollar quoting.  It might be useful when translating
    pre-dollar quoting code into something more comprehensible.
  </para>

  <variablelist>
   <varlistentry>
    <term>1 quotation mark</term>
    <listitem>
     <para>
      To begin and end the function body, for example:
<programlisting>
CREATE FUNCTION foo() RETURNS integer AS '
          ....
' LANGUAGE plpgsql;
</programlisting>
      Anywhere within a single-quoted function body, quote marks
      <emphasis>must</emphasis> appear in pairs.
     </para>
    </listitem>
   </varlistentry>

   <varlistentry>
    <term>2 quotation marks</term>
    <listitem>
     <para>
      For string literals inside the function body, for example:
<programlisting>
a_output := ''Blah'';
SELECT * FROM users WHERE f_name=''foobar'';
</programlisting>
      In the dollar-quoting approach, you'd just write:
<programlisting>
a_output := 'Blah';
SELECT * FROM users WHERE f_name='foobar';
</programlisting>
      which is exactly what the <application>PL/pgSQL</application> parser would see
      in either case.
     </para>
    </listitem>
   </varlistentry>

   <varlistentry>
    <term>4 quotation marks</term>
    <listitem>
     <para>
      When you need a single quotation mark in a string constant inside the
      function body, for example:
<programlisting>
a_output := a_output || '' AND name LIKE ''''foobar'''' AND xyz''
</programlisting>
      The value actually appended to <literal>a_output</literal> would be:
      <literal> AND name LIKE 'foobar' AND xyz</literal>.
     </para>
     <para>
      In the dollar-quoting approach, you'd write:
<programlisting>
a_output := a_output || $$ AND name LIKE 'foobar' AND xyz$$
</programlisting>
      being careful that any dollar-quote delimiters around this are not
      just <literal>$$</literal>.
     </para>
    </listitem>
   </varlistentry>

   <varlistentry>
    <term>6 quotation marks</term>
    <listitem>
     <para>
      When a single quotation mark in a string inside the function body is
      adjacent to the end of that string constant, for example:
<programlisting>
a_output := a_output || '' AND name LIKE ''''foobar''''''
</programlisting>
      The value appended to <literal>a_output</literal> would then be:
      <literal> AND name LIKE 'foobar'</literal>.
     </para>
     <para>
      In the dollar-quoting approach, this becomes:
<programlisting>
a_output := a_output || $$ AND name LIKE 'foobar'$$
</programlisting>
     </para>
    </listitem>
   </varlistentry>

   <varlistentry>
    <term>10 quotation marks</term>
    <listitem>
     <para>
      When you want two single quotation marks in a string constant (which
      accounts for 8 quotation marks) and this is adjacent to the end of that
      string constant (2 more).  You will probably only need that if
      you are writing a function that generates other functions, as in
      <xref linkend="plpgsql-porting-ex2"/>.
      For example:
<programlisting>
a_output := a_output || '' if v_'' ||
    referrer_keys.kind || '' like ''''''''''
    || referrer_keys.key_string || ''''''''''
    then return ''''''  || referrer_keys.referrer_type
    || ''''''; end if;'';
</programlisting>
      The value of <literal>a_output</literal> would then be:
<programlisting>
if v_... like ''...'' then return ''...''; end if;
</programlisting>
     </para>
     <para>
      In the dollar-quoting approach, this becomes:
<programlisting>
a_output := a_output || $$ if v_$$ || referrer_keys.kind || $$ like '$$
    || referrer_keys.key_string || $$'
    then return '$$  || referrer_keys.referrer_type
    || $$'; end if;$$;
</programlisting>
      where we assume we only need to put single quote marks into
      <literal>a_output</literal>, because it will be re-quoted before use.
     </para>
    </listitem>
   </varlistentry>
  </variablelist>

  </sect2>
  <sect2 id="plpgsql-extra-checks">
   <title>Additional Compile-Time and Run-Time Checks</title>

   <para>
    To aid the user in finding instances of simple but common problems before
    they cause harm, <application>PL/pgSQL</application> provides additional
    <replaceable>checks</replaceable>. When enabled, depending on the configuration, they
    can be used to emit either a <literal>WARNING</literal> or an <literal>ERROR</literal>
    during the compilation of a function. A function which has received
    a <literal>WARNING</literal> can be executed without producing further messages,
    so you are advised to test in a separate development environment.
   </para>

   <para>
    Setting <varname>plpgsql.extra_warnings</varname>, or
    <varname>plpgsql.extra_errors</varname>, as appropriate, to <literal>"all"</literal>
    is encouraged in development and/or testing environments.
   </para>

   <para>
    These additional checks are enabled through the configuration variables
    <varname>plpgsql.extra_warnings</varname> for warnings and
    <varname>plpgsql.extra_errors</varname> for errors. Both can be set either to
    a comma-separated list of checks, <literal>"none"</literal> or
    <literal>"all"</literal>. The default is <literal>"none"</literal>. Currently
    the list of available checks includes:
    <variablelist>
     <varlistentry>
      <term><varname>shadowed_variables</varname></term>
      <listitem>
       <para>
        Checks if a declaration shadows a previously defined variable.
       </para>
      </listitem>
     </varlistentry>

     <varlistentry>
      <term><varname>strict_multi_assignment</varname></term>
      <listitem>
       <para>
        Some <application>PL/PgSQL</application> commands allow assigning
        values to more than one variable at a time, such as
        <command>SELECT INTO</command>.  Typically, the number of target
        variables and the number of source variables should match, though
        <application>PL/PgSQL</application> will use <literal>NULL</literal>
        for missing values and extra variables are ignored.  Enabling this
        check will cause <application>PL/PgSQL</application> to throw a
        <literal>WARNING</literal> or <literal>ERROR</literal> whenever the
        number of target variables and the number of source variables are
        different.
       </para>
      </listitem>
     </varlistentry>

     <varlistentry>
      <term><varname>too_many_rows</varname></term>
      <listitem>
       <para>
        Enabling this check will cause <application>PL/PgSQL</application> to
        check if a given query returns more than one row when an
        <literal>INTO</literal> clause is used.  As an <literal>INTO</literal>
        statement will only ever use one row, having a query return multiple
        rows is generally either inefficient and/or nondeterministic and
        therefore is likely an error.
       </para>
      </listitem>
     </varlistentry>
    </variablelist>

    The following example shows the effect of <varname>plpgsql.extra_warnings</varname>
    set to <varname>shadowed_variables</varname>:
<programlisting>
SET plpgsql.extra_warnings TO 'shadowed_variables';

CREATE FUNCTION foo(f1 int) RETURNS int AS $$
DECLARE
f1 int;
BEGIN
RETURN f1;
END;
$$ LANGUAGE plpgsql;
WARNING:  variable "f1" shadows a previously defined variable
LINE 3: f1 int;
        ^
CREATE FUNCTION
</programlisting>
    The below example shows the effects of setting
    <varname>plpgsql.extra_warnings</varname> to
    <varname>strict_multi_assignment</varname>:
<programlisting>
SET plpgsql.extra_warnings TO 'strict_multi_assignment';

CREATE OR REPLACE FUNCTION public.foo()
 RETURNS void
 LANGUAGE plpgsql
AS $$
DECLARE
  x int;
  y int;
BEGIN
  SELECT 1 INTO x, y;
  SELECT 1, 2 INTO x, y;
  SELECT 1, 2, 3 INTO x, y;
END;
$$;

SELECT foo();
WARNING:  number of source and target fields in assignment does not match
DETAIL:  strict_multi_assignment check of extra_warnings is active.
HINT:  Make sure the query returns the exact list of columns.
WARNING:  number of source and target fields in assignment does not match
DETAIL:  strict_multi_assignment check of extra_warnings is active.
HINT:  Make sure the query returns the exact list of columns.

 foo
-----

(1 row)
</programlisting>
   </para>
  </sect2>
 </sect1>

  <!-- **** Porting from Oracle PL/SQL **** -->

 <sect1 id="plpgsql-porting">
  <title>Porting from <productname>Oracle</productname> PL/SQL</title>

  <indexterm zone="plpgsql-porting">
   <primary>Oracle</primary>
   <secondary>porting from PL/SQL to PL/pgSQL</secondary>
  </indexterm>

  <indexterm zone="plpgsql-porting">
   <primary>PL/SQL (Oracle)</primary>
   <secondary>porting to PL/pgSQL</secondary>
  </indexterm>

  <para>
   This section explains differences between
   <productname>PostgreSQL</productname>'s <application>PL/pgSQL</application>
   language and Oracle's <application>PL/SQL</application> language,
   to help developers who port applications from
   <trademark class="registered">Oracle</trademark> to <productname>PostgreSQL</productname>.
  </para>

  <para>
   <application>PL/pgSQL</application> is similar to PL/SQL in many
   aspects. It is a block-structured, imperative language, and all
   variables have to be declared.  Assignments, loops, and conditionals
   are similar.  The main differences you should keep in mind when
   porting from <application>PL/SQL</application> to
   <application>PL/pgSQL</application> are:

    <itemizedlist>
     <listitem>
      <para>
       If a name used in an SQL command could be either a column name of a
       table used in the command or a reference to a variable of the function,
       <application>PL/SQL</application> treats it as a column name.
       By default, <application>PL/pgSQL</application> will throw an error
       complaining that the name is ambiguous.  You can specify
       <literal>plpgsql.variable_conflict</literal> = <literal>use_column</literal>
       to change this behavior to match <application>PL/SQL</application>,
       as explained in <xref linkend="plpgsql-var-subst"/>.
       It's often best to avoid such ambiguities in the first place,
       but if you have to port a large amount of code that depends on
       this behavior, setting <literal>variable_conflict</literal> may be the
       best solution.
      </para>
     </listitem>

     <listitem>
      <para>
       In <productname>PostgreSQL</productname> the function body must be written as
       a string literal.  Therefore you need to use dollar quoting or escape
       single quotes in the function body. (See <xref
       linkend="plpgsql-quote-tips"/>.)
      </para>
     </listitem>

     <listitem>
      <para>
       Data type names often need translation.  For example, in Oracle string
       values are commonly declared as being of type <type>varchar2</type>, which
       is a non-SQL-standard type.  In <productname>PostgreSQL</productname>,
       use type <type>varchar</type> or <type>text</type> instead.  Similarly, replace
       type <type>number</type> with <type>numeric</type>, or use some other numeric
       data type if there's a more appropriate one.
      </para>
     </listitem>

     <listitem>
      <para>
       Instead of packages, use schemas to organize your functions
       into groups.
      </para>
     </listitem>

     <listitem>
      <para>
       Since there are no packages, there are no package-level variables
       either. This is somewhat annoying.  You can keep per-session state
       in temporary tables instead.
      </para>
     </listitem>

     <listitem>
      <para>
       Integer <command>FOR</command> loops with <literal>REVERSE</literal> work
       differently: <application>PL/SQL</application> counts down from the second
       number to the first, while <application>PL/pgSQL</application> counts down
       from the first number to the second, requiring the loop bounds
       to be swapped when porting.  This incompatibility is unfortunate
       but is unlikely to be changed. (See <xref
       linkend="plpgsql-integer-for"/>.)
      </para>
     </listitem>

     <listitem>
      <para>
       <command>FOR</command> loops over queries (other than cursors) also work
       differently: the target variable(s) must have been declared,
       whereas <application>PL/SQL</application> always declares them implicitly.
       An advantage of this is that the variable values are still accessible
       after the loop exits.
      </para>
     </listitem>

     <listitem>
      <para>
       There are various notational differences for the use of cursor
       variables.
      </para>
     </listitem>

    </itemizedlist>
   </para>

  <sect2>
   <title>Porting Examples</title>

   <para>
    <xref linkend="pgsql-porting-ex1"/> shows how to port a simple
    function from <application>PL/SQL</application> to <application>PL/pgSQL</application>.
   </para>

   <example id="pgsql-porting-ex1">
    <title>Porting a Simple Function from <application>PL/SQL</application> to <application>PL/pgSQL</application></title>

    <para>
     Here is an <productname>Oracle</productname> <application>PL/SQL</application> function:
<programlisting>
CREATE OR REPLACE FUNCTION cs_fmt_browser_version(v_name varchar2,
                                                  v_version varchar2)
RETURN varchar2 IS
BEGIN
    IF v_version IS NULL THEN
        RETURN v_name;
    END IF;
    RETURN v_name || '/' || v_version;
END;
/
show errors;
</programlisting>
    </para>

    <para>
     Let's go through this function and see the differences compared to
     <application>PL/pgSQL</application>:

     <itemizedlist>
      <listitem>
       <para>
        The type name <type>varchar2</type> has to be changed to <type>varchar</type>
        or <type>text</type>.  In the examples in this section, we'll
        use <type>varchar</type>, but <type>text</type> is often a better choice if
        you do not need specific string length limits.
       </para>
      </listitem>

      <listitem>
       <para>
        The <literal>RETURN</literal> key word in the function
        prototype (not the function body) becomes
        <literal>RETURNS</literal> in
        <productname>PostgreSQL</productname>.
        Also, <literal>IS</literal> becomes <literal>AS</literal>, and you need to
        add a <literal>LANGUAGE</literal> clause because <application>PL/pgSQL</application>
        is not the only possible function language.
       </para>
      </listitem>

      <listitem>
       <para>
        In <productname>PostgreSQL</productname>, the function body is considered
        to be a string literal, so you need to use quote marks or dollar
        quotes around it.  This substitutes for the terminating <literal>/</literal>
        in the Oracle approach.
       </para>
      </listitem>

      <listitem>
       <para>
        The <literal>show errors</literal> command does not exist in
        <productname>PostgreSQL</productname>, and is not needed since errors are
        reported automatically.
       </para>
      </listitem>
     </itemizedlist>
    </para>

    <para>
     This is how this function would look when ported to
     <productname>PostgreSQL</productname>:

<programlisting>
CREATE OR REPLACE FUNCTION cs_fmt_browser_version(v_name varchar,
                                                  v_version varchar)
RETURNS varchar AS $$
BEGIN
    IF v_version IS NULL THEN
        RETURN v_name;
    END IF;
    RETURN v_name || '/' || v_version;
END;
$$ LANGUAGE plpgsql;
</programlisting>
    </para>
   </example>

   <para>
    <xref linkend="plpgsql-porting-ex2"/> shows how to port a
    function that creates another function and how to handle the
    ensuing quoting problems.
   </para>

   <example id="plpgsql-porting-ex2">
    <title>Porting a Function that Creates Another Function from <application>PL/SQL</application> to <application>PL/pgSQL</application></title>

    <para>
     The following procedure grabs rows from a
     <command>SELECT</command> statement and builds a large function
     with the results in <literal>IF</literal> statements, for the
     sake of efficiency.
    </para>

    <para>
     This is the Oracle version:
<programlisting>
CREATE OR REPLACE PROCEDURE cs_update_referrer_type_proc IS
    CURSOR referrer_keys IS
        SELECT * FROM cs_referrer_keys
        ORDER BY try_order;
    func_cmd VARCHAR(4000);
BEGIN
    func_cmd := 'CREATE OR REPLACE FUNCTION cs_find_referrer_type(v_host IN VARCHAR2,
                 v_domain IN VARCHAR2, v_url IN VARCHAR2) RETURN VARCHAR2 IS BEGIN';

    FOR referrer_key IN referrer_keys LOOP
        func_cmd := func_cmd ||
          ' IF v_' || referrer_key.kind
          || ' LIKE ''' || referrer_key.key_string
          || ''' THEN RETURN ''' || referrer_key.referrer_type
          || '''; END IF;';
    END LOOP;

    func_cmd := func_cmd || ' RETURN NULL; END;';

    EXECUTE IMMEDIATE func_cmd;
END;
/
show errors;
</programlisting>
    </para>

    <para>
     Here is how this function would end up in <productname>PostgreSQL</productname>:
<programlisting>
CREATE OR REPLACE PROCEDURE cs_update_referrer_type_proc() AS $func$
DECLARE
    referrer_keys CURSOR IS
        SELECT * FROM cs_referrer_keys
        ORDER BY try_order;
    func_body text;
    func_cmd text;
BEGIN
    func_body := 'BEGIN';

    FOR referrer_key IN referrer_keys LOOP
        func_body := func_body ||
          ' IF v_' || referrer_key.kind
          || ' LIKE ' || quote_literal(referrer_key.key_string)
          || ' THEN RETURN ' || quote_literal(referrer_key.referrer_type)
          || '; END IF;' ;
    END LOOP;

    func_body := func_body || ' RETURN NULL; END;';

    func_cmd :=
      'CREATE OR REPLACE FUNCTION cs_find_referrer_type(v_host varchar,
                                                        v_domain varchar,
                                                        v_url varchar)
        RETURNS varchar AS '
      || quote_literal(func_body)
      || ' LANGUAGE plpgsql;' ;

    EXECUTE func_cmd;
END;
$func$ LANGUAGE plpgsql;
</programlisting>
     Notice how the body of the function is built separately and passed
     through <literal>quote_literal</literal> to double any quote marks in it.  This
     technique is needed because we cannot safely use dollar quoting for
     defining the new function: we do not know for sure what strings will
     be interpolated from the <structfield>referrer_key.key_string</structfield> field.
     (We are assuming here that <structfield>referrer_key.kind</structfield> can be
     trusted to always be <literal>host</literal>, <literal>domain</literal>, or
     <literal>url</literal>, but <structfield>referrer_key.key_string</structfield> might be
     anything, in particular it might contain dollar signs.) This function
     is actually an improvement on the Oracle original, because it will
     not generate broken code when <structfield>referrer_key.key_string</structfield> or
     <structfield>referrer_key.referrer_type</structfield> contain quote marks.
    </para>
   </example>

   <para>
    <xref linkend="plpgsql-porting-ex3"/> shows how to port a function
    with <literal>OUT</literal> parameters and string manipulation.
    <productname>PostgreSQL</productname> does not have a built-in
    <function>instr</function> function, but you can create one
    using a combination of other
    functions. In <xref linkend="plpgsql-porting-appendix"/> there is a
    <application>PL/pgSQL</application> implementation of
    <function>instr</function> that you can use to make your porting
    easier.
   </para>

   <example id="plpgsql-porting-ex3">
    <title>Porting a Procedure With String Manipulation and
    <literal>OUT</literal> Parameters from <application>PL/SQL</application> to
    <application>PL/pgSQL</application></title>

    <para>
     The following <productname>Oracle</productname> PL/SQL procedure is used
     to parse a URL and return several elements (host, path, and query).
    </para>

    <para>
     This is the Oracle version:
<programlisting>
CREATE OR REPLACE PROCEDURE cs_parse_url(
    v_url IN VARCHAR2,
    v_host OUT VARCHAR2,  -- This will be passed back
    v_path OUT VARCHAR2,  -- This one too
    v_query OUT VARCHAR2) -- And this one
IS
    a_pos1 INTEGER;
    a_pos2 INTEGER;
BEGIN
    v_host := NULL;
    v_path := NULL;
    v_query := NULL;
    a_pos1 := instr(v_url, '//');

    IF a_pos1 = 0 THEN
        RETURN;
    END IF;
    a_pos2 := instr(v_url, '/', a_pos1 + 2);
    IF a_pos2 = 0 THEN
        v_host := substr(v_url, a_pos1 + 2);
        v_path := '/';
        RETURN;
    END IF;

    v_host := substr(v_url, a_pos1 + 2, a_pos2 - a_pos1 - 2);
    a_pos1 := instr(v_url, '?', a_pos2 + 1);

    IF a_pos1 = 0 THEN
        v_path := substr(v_url, a_pos2);
        RETURN;
    END IF;

    v_path := substr(v_url, a_pos2, a_pos1 - a_pos2);
    v_query := substr(v_url, a_pos1 + 1);
END;
/
show errors;
</programlisting>
    </para>

    <para>
     Here is a possible translation into <application>PL/pgSQL</application>:
<programlisting>
CREATE OR REPLACE FUNCTION cs_parse_url(
    v_url IN VARCHAR,
    v_host OUT VARCHAR,  -- This will be passed back
    v_path OUT VARCHAR,  -- This one too
    v_query OUT VARCHAR) -- And this one
AS $$
DECLARE
    a_pos1 INTEGER;
    a_pos2 INTEGER;
BEGIN
    v_host := NULL;
    v_path := NULL;
    v_query := NULL;
    a_pos1 := instr(v_url, '//');

    IF a_pos1 = 0 THEN
        RETURN;
    END IF;
    a_pos2 := instr(v_url, '/', a_pos1 + 2);
    IF a_pos2 = 0 THEN
        v_host := substr(v_url, a_pos1 + 2);
        v_path := '/';
        RETURN;
    END IF;

    v_host := substr(v_url, a_pos1 + 2, a_pos2 - a_pos1 - 2);
    a_pos1 := instr(v_url, '?', a_pos2 + 1);

    IF a_pos1 = 0 THEN
        v_path := substr(v_url, a_pos2);
        RETURN;
    END IF;

    v_path := substr(v_url, a_pos2, a_pos1 - a_pos2);
    v_query := substr(v_url, a_pos1 + 1);
END;
$$ LANGUAGE plpgsql;
</programlisting>

     This function could be used like this:
<programlisting>
SELECT * FROM cs_parse_url('http://foobar.com/query.cgi?baz');
</programlisting>
    </para>
   </example>

   <para>
    <xref linkend="plpgsql-porting-ex4"/> shows how to port a procedure
    that uses numerous features that are specific to Oracle.
   </para>

   <example id="plpgsql-porting-ex4">
    <title>Porting a Procedure from <application>PL/SQL</application> to <application>PL/pgSQL</application></title>

    <para>
     The Oracle version:

<programlisting>
CREATE OR REPLACE PROCEDURE cs_create_job(v_job_id IN INTEGER) IS
    a_running_job_count INTEGER;
BEGIN
    LOCK TABLE cs_jobs IN EXCLUSIVE MODE;

    SELECT count(*) INTO a_running_job_count FROM cs_jobs WHERE end_stamp IS NULL;

    IF a_running_job_count &gt; 0 THEN
        COMMIT; -- free lock
        raise_application_error(-20000,
                 'Unable to create a new job: a job is currently running.');
    END IF;

    DELETE FROM cs_active_job;
    INSERT INTO cs_active_job(job_id) VALUES (v_job_id);

    BEGIN
        INSERT INTO cs_jobs (job_id, start_stamp) VALUES (v_job_id, now());
    EXCEPTION
        WHEN dup_val_on_index THEN NULL; -- don't worry if it already exists
    END;
    COMMIT;
END;
/
show errors
</programlisting>
   </para>

   <para>
    This is how we could port this procedure to <application>PL/pgSQL</application>:

<programlisting>
CREATE OR REPLACE PROCEDURE cs_create_job(v_job_id integer) AS $$
DECLARE
    a_running_job_count integer;
BEGIN
    LOCK TABLE cs_jobs IN EXCLUSIVE MODE;

    SELECT count(*) INTO a_running_job_count FROM cs_jobs WHERE end_stamp IS NULL;

    IF a_running_job_count &gt; 0 THEN
        COMMIT; -- free lock
        RAISE EXCEPTION 'Unable to create a new job: a job is currently running'; -- <co id="co.plpgsql-porting-raise"/>
    END IF;

    DELETE FROM cs_active_job;
    INSERT INTO cs_active_job(job_id) VALUES (v_job_id);

    BEGIN
        INSERT INTO cs_jobs (job_id, start_stamp) VALUES (v_job_id, now());
    EXCEPTION
        WHEN unique_violation THEN -- <co id="co.plpgsql-porting-exception"/>
            -- don't worry if it already exists
    END;
    COMMIT;
END;
$$ LANGUAGE plpgsql;
</programlisting>

    <calloutlist>
     <callout arearefs="co.plpgsql-porting-raise">
      <para>
       The syntax of <literal>RAISE</literal> is considerably different from
       Oracle's statement, although the basic case <literal>RAISE</literal>
       <replaceable class="parameter">exception_name</replaceable> works
       similarly.
      </para>
     </callout>
     <callout arearefs="co.plpgsql-porting-exception">
      <para>
       The exception names supported by <application>PL/pgSQL</application> are
       different from Oracle's.  The set of built-in exception names
       is much larger (see <xref linkend="errcodes-appendix"/>).  There
       is not currently a way to declare user-defined exception names,
       although you can throw user-chosen SQLSTATE values instead.
      </para>
     </callout>
    </calloutlist>
   </para>
   </example>
  </sect2>

  <sect2 id="plpgsql-porting-other">
   <title>Other Things to Watch For</title>

   <para>
    This section explains a few other things to watch for when porting
    Oracle <application>PL/SQL</application> functions to
    <productname>PostgreSQL</productname>.
   </para>

   <sect3 id="plpgsql-porting-exceptions">
    <title>Implicit Rollback after Exceptions</title>

    <para>
     In <application>PL/pgSQL</application>, when an exception is caught by an
     <literal>EXCEPTION</literal> clause, all database changes since the block's
     <literal>BEGIN</literal> are automatically rolled back.  That is, the behavior
     is equivalent to what you'd get in Oracle with:

<programlisting>
BEGIN
    SAVEPOINT s1;
    ... code here ...
EXCEPTION
    WHEN ... THEN
        ROLLBACK TO s1;
        ... code here ...
    WHEN ... THEN
        ROLLBACK TO s1;
        ... code here ...
END;
</programlisting>

     If you are translating an Oracle procedure that uses
     <command>SAVEPOINT</command> and <command>ROLLBACK TO</command> in this style,
     your task is easy: just omit the <command>SAVEPOINT</command> and
     <command>ROLLBACK TO</command>.  If you have a procedure that uses
     <command>SAVEPOINT</command> and <command>ROLLBACK TO</command> in a different way
     then some actual thought will be required.
    </para>
   </sect3>

   <sect3>
    <title><command>EXECUTE</command></title>

    <para>
     The <application>PL/pgSQL</application> version of
     <command>EXECUTE</command> works similarly to the
     <application>PL/SQL</application> version, but you have to remember to use
     <function>quote_literal</function> and
     <function>quote_ident</function> as described in <xref
     linkend="plpgsql-statements-executing-dyn"/>.  Constructs of the
     type <literal>EXECUTE 'SELECT * FROM $1';</literal> will not work
     reliably unless you use these functions.
    </para>
   </sect3>

   <sect3 id="plpgsql-porting-optimization">
    <title>Optimizing <application>PL/pgSQL</application> Functions</title>

    <para>
     <productname>PostgreSQL</productname> gives you two function creation
     modifiers to optimize execution: <quote>volatility</quote> (whether
     the function always returns the same result when given the same
     arguments) and <quote>strictness</quote> (whether the function
     returns null if any argument is null).  Consult the <xref
     linkend="sql-createfunction"/>
     reference page for details.
    </para>

    <para>
     When making use of these optimization attributes, your
     <command>CREATE FUNCTION</command> statement might look something
     like this:

<programlisting>
CREATE FUNCTION foo(...) RETURNS integer AS $$
...
$$ LANGUAGE plpgsql STRICT IMMUTABLE;
</programlisting>
    </para>
   </sect3>
  </sect2>

  <sect2 id="plpgsql-porting-appendix">
   <title>Appendix</title>

   <para>
    This section contains the code for a set of Oracle-compatible
    <function>instr</function> functions that you can use to simplify
    your porting efforts.
   </para>

   <indexterm>
    <primary><function>instr</function> function</primary>
   </indexterm>

<programlisting><![CDATA[
--
-- instr functions that mimic Oracle's counterpart
-- Syntax: instr(string1, string2 [, n [, m]])
-- where [] denotes optional parameters.
--
-- Search string1, beginning at the nth character, for the mth occurrence
-- of string2.  If n is negative, search backwards, starting at the abs(n)'th
-- character from the end of string1.
-- If n is not passed, assume 1 (search starts at first character).
-- If m is not passed, assume 1 (find first occurrence).
-- Returns starting index of string2 in string1, or 0 if string2 is not found.
--

CREATE FUNCTION instr(varchar, varchar) RETURNS integer AS $$
BEGIN
    RETURN instr($1, $2, 1);
END;
$$ LANGUAGE plpgsql STRICT IMMUTABLE;


CREATE FUNCTION instr(string varchar, string_to_search_for varchar,
                      beg_index integer)
RETURNS integer AS $$
DECLARE
    pos integer NOT NULL DEFAULT 0;
    temp_str varchar;
    beg integer;
    length integer;
    ss_length integer;
BEGIN
    IF beg_index > 0 THEN
        temp_str := substring(string FROM beg_index);
        pos := position(string_to_search_for IN temp_str);

        IF pos = 0 THEN
            RETURN 0;
        ELSE
            RETURN pos + beg_index - 1;
        END IF;
    ELSIF beg_index < 0 THEN
        ss_length := char_length(string_to_search_for);
        length := char_length(string);
        beg := length + 1 + beg_index;

        WHILE beg > 0 LOOP
            temp_str := substring(string FROM beg FOR ss_length);
            IF string_to_search_for = temp_str THEN
                RETURN beg;
            END IF;

            beg := beg - 1;
        END LOOP;

        RETURN 0;
    ELSE
        RETURN 0;
    END IF;
END;
$$ LANGUAGE plpgsql STRICT IMMUTABLE;


CREATE FUNCTION instr(string varchar, string_to_search_for varchar,
                      beg_index integer, occur_index integer)
RETURNS integer AS $$
DECLARE
    pos integer NOT NULL DEFAULT 0;
    occur_number integer NOT NULL DEFAULT 0;
    temp_str varchar;
    beg integer;
    i integer;
    length integer;
    ss_length integer;
BEGIN
    IF occur_index <= 0 THEN
        RAISE 'argument ''%'' is out of range', occur_index
          USING ERRCODE = '22003';
    END IF;

    IF beg_index > 0 THEN
        beg := beg_index - 1;
        FOR i IN 1..occur_index LOOP
            temp_str := substring(string FROM beg + 1);
            pos := position(string_to_search_for IN temp_str);
            IF pos = 0 THEN
                RETURN 0;
            END IF;
            beg := beg + pos;
        END LOOP;

        RETURN beg;
    ELSIF beg_index < 0 THEN
        ss_length := char_length(string_to_search_for);
        length := char_length(string);
        beg := length + 1 + beg_index;

        WHILE beg > 0 LOOP
            temp_str := substring(string FROM beg FOR ss_length);
            IF string_to_search_for = temp_str THEN
                occur_number := occur_number + 1;
                IF occur_number = occur_index THEN
                    RETURN beg;
                END IF;
            END IF;

            beg := beg - 1;
        END LOOP;

        RETURN 0;
    ELSE
        RETURN 0;
    END IF;
END;
$$ LANGUAGE plpgsql STRICT IMMUTABLE;
]]>
</programlisting>
  </sect2>

 </sect1>

</chapter>