Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
summaryrefslogtreecommitdiff
blob: f994cbe0a07ac8bbbf6d438417c4dd439a9f882d (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
<!--
$Header: /cvsroot/pgsql/doc/src/sgml/syntax.sgml,v 1.36 2001/01/21 22:02:01 petere Exp $
-->

<chapter id="sql-syntax">
 <title>SQL Syntax</title>

  <abstract>
   <para>
    A description of the general syntax of SQL.
   </para>
  </abstract>

 <sect1 id="sql-syntax-lexical">
  <title>Lexical Structure</title>

  <para>
   SQL input consists of a sequence of
   <firstterm>commands</firstterm>.  A command is composed of a
   sequence of <firstterm>tokens</firstterm>, terminated by a
   semicolon (<quote>;</quote>).  The end of the input stream also
   terminates a command.  Which tokens are valid depends on the syntax
   of the particular command.
  </para>

  <para>
   A token can be a <firstterm>key word</firstterm>, an
   <firstterm>identifier</firstterm>, a <firstterm>quoted
   identifier</firstterm>, a <firstterm>literal</firstterm> (or
   constant), or a special character symbol.  Tokens are normally
   separated by whitespace (space, tab, newline), but need not be if
   there is no ambiguity (which is generally only the case if a
   special character is adjacent to some other token type).
  </para>

  <para>
   Additionally, <firstterm>comments</firstterm> can occur in SQL
   input.  They are not tokens, they are effectively equivalent to
   whitespace.
  </para>

  <informalexample id="sql-syntax-ex-commands">
   <para>
    For example, the following is (syntactically) valid SQL input:
<programlisting>
SELECT * FROM MY_TABLE;
UPDATE MY_TABLE SET A = 5;
INSERT INTO MY_TABLE VALUES (3, 'hi there');
</programlisting>
    This is a sequence of three commands, one per line (although this
    is not required; more than one command can be on a line, and
    commands can be usefully split across lines).
   </para>
  </informalexample>

  <para>
   The SQL syntax is not very consistent regarding what tokens
   identify commands and which are operands or parameters.  The first
   few tokens are generally the command name, so in the above example
   we would usually speak of a <quote>SELECT</quote>, an
   <quote>UPDATE</quote>, and an <quote>INSERT</quote> command.  But
   for instance the <command>UPDATE</command> command always requires
   a <token>SET</token> token to appear in a certain position, and
   this particular variation of <command>INSERT</command> also
   requires a <token>VALUES</token> in order to be complete.  The
   precise syntax rules for each command are described in the
   <citetitle>Reference Manual</citetitle>.
  </para>

  <sect2 id="sql-syntax-identifiers">
   <title>Identifiers and Key Words</title>

   <para>
    Tokens such as <token>SELECT</token>, <token>UPDATE</token>, or
    <token>VALUES</token> in the example above are examples of
    <firstterm>key words</firstterm>, that is, words that have a fixed
    meaning in the SQL language.  The tokens <token>MY_TABLE</token>
    and <token>A</token> are examples of
    <firstterm>identifiers</firstterm>.  They identify names of
    tables, columns, or other database objects, depending on the
    command they are used in.  Therefore they are sometimes simply
    called <quote>names</quote>.  Key words and identifiers have the
    same lexical structure, meaning that one cannot know whether a
    token is an identifier or a key word without knowing the language.
    A complete list of key words can be found in <xref
    linkend="sql-keywords-appendix">.
   </para>

   <para>
    SQL identifiers and key words must begin with a letter
    (<literal>a</literal>-<literal>z</literal>) or underscore
    (<literal>_</literal>).  Subsequent characters in an identifier or
    key word can be letters, digits
    (<literal>0</literal>-<literal>9</literal>), or underscores,
    although the SQL standard will not define a key word that contains
    digits or starts or ends with an underscore.
   </para>

   <para>
    The system uses no more than <symbol>NAMEDATALEN</symbol>-1
    characters of an identifier; longer names can be written in
    commands, but they will be truncated.  By default,
    <symbol>NAMEDATALEN</symbol> is 32 so the maximum identifier length
    is 31 (but at the time the system is built,
    <symbol>NAMEDATALEN</symbol> can be changed in
    <filename>src/include/postgres_ext.h</filename>).
   </para>

   <para>
    Identifier and key word names are case insensitive.  Therefore
<programlisting>
UPDATE MY_TABLE SET A = 5;
</programlisting>
    can equivalently be written as
<programlisting>
uPDaTE my_TabLE SeT a = 5;
</programlisting>
    A good convention to adopt is perhaps to write key words in upper
    case and names in lower case, e.g.,
<programlisting>
UPDATE my_table SET a = 5;
</programlisting>
   </para>

   <para>
    There is a second kind of identifier:  the <firstterm>delimited
    identifier</firstterm> or <firstterm>quoted
    identifier</firstterm>.  It is formed by enclosing an arbitrary
    sequence of characters in double-quotes
    (<literal>"</literal>). <!-- " font-lock mania --> A delimited
    identifier is always an identifier, never a key word.  So
    <literal>"select"</literal> could be used to refer to a column or
    table named <quote>select</quote>, whereas an unquoted
    <literal>select</literal> would be taken as part of a command and
    would therefore provoke a parse error when used where a table or
    column name is expected.  The example can be written with quoted
    identifiers like so:
<programlisting>
UPDATE "my_table" SET "a" = 5;
</programlisting>
   </para>

   <para>
    Quoted identifiers can contain any character other than a double
    quote itself.  This allows constructing table or column names that
    would otherwise not be possible, such as ones containing spaces or
    ampersands.  The length limitation still applies.
   </para>

   <para>
    Quoting an identifier also makes it case-sensitive, whereas
    unquoted names are always folded to lower case.  For example, the
    identifiers <literal>FOO</literal>, <literal>foo</literal> and
    <literal>"foo"</literal> are considered the same by
    <productname>Postgres</productname>, but <literal>"Foo"</literal>
    and <literal>"FOO"</literal> are different from these three and
    each other.
    <footnote>
     <para>
      This is incompatible with SQL, where unquoted names are folded to
      upper case.  Thus, <literal>foo</literal> is equivalent to
      <literal>"FOO"</literal>.  If you want to write portable
      applications you are advised to always quote a particular name or
      never quote it.
     </para>
    </footnote>
   </para>
  </sect2>


  <sect2 id="sql-syntax-constants">
   <title>Constants</title>

   <para>
    There are four kinds of <firstterm>implicitly typed
    constants</firstterm> in <productname>Postgres</productname>:
    strings, bit strings, integers, and floating point numbers.
    Constants can also be specified with explicit types, which can
    enable more accurate representation and more efficient handling by
    the system. The implicit constants are described below; explicit
    constants are discussed afterwards.
   </para>

   <sect3 id="sql-syntax-strings">
    <title>String Constants</title>

    <para>
     A string constant in SQL is an arbitrary sequence of characters
     bounded by single quotes (<quote>'</quote>), e.g., <literal>'This
     is a string'</literal>.  SQL allows single quotes to be embedded
     in strings by typing two adjacent single quotes (e.g.,
     <literal>'Dianne''s horse'</literal>).  In
     <productname>Postgres</productname> single quotes may
     alternatively be escaped with a backslash (<quote>\</quote>,
     e.g., <literal>'Dianne\'s horse'</literal>).
    </para>

    <para>
     C-style backslash escapes are also available:
     <literal>\b</literal> is a backspace, <literal>\f</literal> is a
     form feed, <literal>\n</literal> is a newline,
     <literal>\r</literal> is a carriage return, <literal>\t</literal>
     is a tab, and <literal>\<replaceable>xxx</replaceable></literal>,
     where <replaceable>xxx</replaceable> is an octal number, is the
     character with the corresponding ASCII code.  Any other character
     following a backslash is taken literally.  Thus, to include a
     backslash in a string constant, type two backslashes.
    </para>

    <para>
     The character with the code zero cannot be in a string constant.
    </para>

    <para>
     Two string constants that are only separated by whitespace
     <emphasis>with at least one newline</emphasis> are concatenated
     and effectively treated as if the string had been written in one
     constant.  For example:
<programlisting>
SELECT 'foo'
'bar';
</programlisting>
     is equivalent to
<programlisting>
SELECT 'foobar';
</programlisting>
     but
<programlisting>
SELECT 'foo'      'bar';
</programlisting>
     is not valid syntax.
    </para>
   </sect3>

   <sect3 id="sql-syntax-bit-strings">
    <title>Bit String Constants</title>

    <para>
     Bit string constants look like string constants with a
     <literal>B</literal> (upper or lower case) immediately before the
     opening quote (no intervening whitespace), e.g.,
     <literal>B'1001'</literal>.  The only characters allowed within
     bit string constants are <literal>0</literal> and
     <literal>1</literal>.  Bit strings constants can be continued
     across lines in the same way as regular string constants.
    </para>
   </sect3>

   <sect3>
    <title>Integer Constants</title>

    <para>
     Integer constants in SQL are sequences of decimal digits (0
     though 9) with no decimal point.  The range of legal values
     depends on which integer data type is used, but the plain
     <type>integer</type> type accepts values ranging from -2147483648
     to +2147483647.  (The optional plus or minus sign is actually a
     separate unary operator and not part of the integer constant.)
    </para>
   </sect3>

   <sect3>
    <title>Floating Point Constants</title>

    <para>
     Floating point constants are accepted in these general forms:
<synopsis>
<replaceable>digits</replaceable>.<optional><replaceable>digits</replaceable></optional><optional>e<optional>+-</optional><replaceable>digits</replaceable></optional>
<optional><replaceable>digits</replaceable></optional>.<replaceable>digits</replaceable><optional>e<optional>+-</optional><replaceable>digits</replaceable></optional>
<replaceable>digits</replaceable>e<optional>+-</optional><replaceable>digits</replaceable>
</synopsis>
     where <replaceable>digits</replaceable> is one or more decimal
     digits.  At least one digit must be before or after the decimal
     point and after the <literal>e</literal> if you use that option.
     Thus, a floating point constant is distinguished from an integer
     constant by the presence of either the decimal point or the
     exponent clause (or both).  There must not be a space or other
     characters embedded in the constant.
    </para>

    <informalexample>
     <para>
      These are some examples of valid floating point constants:
<literallayout>
3.5
4.
.001
5e2
1.925e-3
</literallayout>
     </para>
    </informalexample>

    <para>
     Floating point constants are of type <type>DOUBLE
     PRECISION</type>. <type>REAL</type> can be specified explicitly
     by using <acronym>SQL</acronym> string notation or
     <productname>Postgres</productname> type notation:

<programlisting>
REAL '1.23'  -- string style
'1.23'::REAL -- Postgres (historical) style
     </programlisting>
    </para>
   </sect3>

   <sect3>
    <title>Constants of Other Types</title>

    <para>
     A constant of an <emphasis>arbitrary</emphasis> type can be
     entered using any one of the following notations:
<synopsis>
<replaceable>type</replaceable> '<replaceable>string</replaceable>'
'<replaceable>string</replaceable>'::<replaceable>type</replaceable>
CAST ( '<replaceable>string</replaceable>' AS <replaceable>type</replaceable> )
</synopsis>
     The value inside the string is passed to the input conversion
     routine for the type called <replaceable>type</replaceable>. The
     result is a constant of the indicated type.  The explicit type
     cast may be omitted if there is no ambiguity as to the type the
     constant must be (for example, when it is passed as an argument
     to a non-overloaded function), in which case it is automatically
     coerced.
    </para>

    <para>
     It is also possible to specify a type coercion using a function-like
     syntax:
<synopsis>
<replaceable>typename</replaceable> ( <replaceable>value</replaceable> )
</synopsis>
     although this only works for types whose names are also valid as
     function names.  (For example, <literal>double precision</literal>
     can't be used this way --- but the equivalent <literal>float8</literal>
     can.)
    </para>

    <para>
     The <literal>::</literal>, <literal>CAST()</literal>, and
     function-call syntaxes can also be used to specify the type of
     arbitrary expressions, but the form
     <replaceable>type</replaceable>
     '<replaceable>string</replaceable>' can only be used to specify
     the type of a literal constant.
    </para>
   </sect3>

   <sect3>
    <title>Array constants</title>

    <para>
     The general format of an array constant is the following:
<synopsis>
'{ <replaceable>val1</replaceable> <replaceable>delim</replaceable> <replaceable>val2</replaceable> <replaceable>delim</replaceable> ... }'
</synopsis>
     where <replaceable>delim</replaceable> is the delimiter character
     for the type, as recorded in its <literal>pg_type</literal>
     entry.  (For all built-in types, this is the comma character
     ",".)  Each <replaceable>val</replaceable> is either a constant
     of the array element type, or a sub-array.  An example of an
     array constant is
<programlisting>
'{{1,2,3},{4,5,6},{7,8,9}}'
</programlisting>
     This constant is a two-dimensional, 3 by 3 array consisting of three
     sub-arrays of integers.
    </para>

    <para>
     Individual array elements can be placed between double-quote
     marks (<literal>"</literal>) <!-- " --> to avoid ambiguity
     problems with respect to white space.  Without quote marks, the
     array-value parser will skip leading white space.
    </para>

    <para>
     (Array constants are actually only a special case of the generic
     type constants discussed in the previous section.  The constant
     is initially treated as a string and passed to the array input
     conversion routine.  An explicit type specification might be
     necessary.)
    </para>
   </sect3>
  </sect2>


  <sect2 id="sql-syntax-operators">
   <title>Operators</title>

   <para>
    An operator is a sequence of up to <symbol>NAMEDATALEN</symbol>-1
    (31 by default) characters from the following list:
<literallayout>
+ - * / &lt; &gt; = ~ ! @ # % ^ &amp; | ` ? $
</literallayout>

    There are a few restrictions on operator names, however:
    <itemizedlist>
     <listitem>
      <para>
       "$" (dollar) cannot be a single-character operator, although it
       can be part of a multi-character operator name.
      </para>
     </listitem>

     <listitem>
      <para>
       <literal>--</literal> and <literal>/*</literal> cannot appear
       anywhere in an operator name, since they will be taken as the
       start of a comment.
      </para>
     </listitem>

     <listitem>
      <para>
       A multi-character operator name cannot end in "+" or "-",
       unless the name also contains at least one of these characters:
<literallayout>
~ ! @ # % ^ &amp; | ` ? $
</literallayout>
       For example, <literal>@-</literal> is an allowed operator name,
       but <literal>*-</literal> is not.  This restriction allows
       <productname>Postgres</productname> to parse SQL-compliant
       queries without requiring spaces between tokens.
      </para>
     </listitem>
    </itemizedlist>
   </para>

   <para>
    When working with non-SQL-standard operator names, you will usually
    need to separate adjacent operators with spaces to avoid ambiguity.
    For example, if you have defined a left-unary operator named "@",
    you cannot write <literal>X*@Y</literal>; you must write
    <literal>X* @Y</literal> to ensure that
    <productname>Postgres</productname> reads it as two operator names
    not one.
   </para>
  </sect2>

  <sect2>
   <title>Special Characters</title>

  <para>
   Some characters that are not alphanumeric have a special meaning
   that is different from being an operator.  Details on the usage can
   be found at the location where the respective syntax element is
   described.  This section only exists to advise the existence and
   summarize the purposes of these characters.

   <itemizedlist>
    <listitem>
     <para>
      A dollar sign (<literal>$</literal>) followed by digits is used
      to represent the positional parameters in the body of a function
      definition.  In other contexts the dollar sign may be part of an
      operator name.
     </para>
    </listitem>

    <listitem>
     <para>
      Parentheses (<literal>()</literal>) have their usual meaning to
      group expressions and enforce precedence.  In some cases
      parentheses are required as part of the fixed syntax of a
      particular SQL command.
     </para>
    </listitem>

    <listitem>
     <para>
      Brackets (<literal>[]</literal>) are used to select the elements
      of an array.  See <xref linkend="arrays"> for more information
      on arrays.
     </para>
    </listitem>

    <listitem>
     <para>
      Commas (<literal>,</literal>) are used in some syntactical
      constructs to separate the elements of a list.
     </para>
    </listitem>

    <listitem>
     <para>
      The semicolon (<literal>;</literal>) terminates an SQL command.
      It cannot appear anywhere within a command, except when quoted
      as a string constant or identifier.
     </para>
    </listitem>

    <listitem>
     <para>
      The colon (<literal>:</literal>) is used to select
      <quote>slices</quote> from arrays. (See <xref
      linkend="arrays">.)  In certain SQL dialects (such as Embedded
      SQL), the colon is used to prefix variable names.
     </para>
    </listitem>

    <listitem>
     <para>
      The asterisk (<literal>*</literal>) has a special meaning when
      used in the <command>SELECT</command> command or with the
      <function>COUNT</function> aggregate function.
     </para>
    </listitem>

    <listitem>
     <para>
      The period (<literal>.</literal>) is used in floating point
      constants, and to separate table and column names.
     </para>
    </listitem>
   </itemizedlist>

   </para>
  </sect2>

  <sect2 id="sql-syntax-comments">
   <title>Comments</title>

   <para>
    A comment is an arbitrary sequence of characters beginning with
    double dashes and extending to the end of the line, e.g.:
<programlisting>
-- This is a standard SQL92 comment
</programlisting>
   </para>

   <para>
    Alternatively, C-style block comments can be used:
<programlisting>
/* multi-line comment
 * with nesting: /* nested block comment */
 */
</programlisting>
    where the comment begins with <literal>/*</literal> and extends to
    the matching occurrence of <literal>*/</literal>. These block
    comments nest, as specified in SQL99 but unlike C, so that one can
    comment out larger blocks of code that may contain existing block
    comments.
   </para>

   <para>
    A comment is removed from the input stream before further syntax
    analysis and is effectively replaced by whitespace.
   </para>
  </sect2>
 </sect1>


  <sect1 id="sql-syntax-columns">
   <title>Columns</title>

    <para>
     A <firstterm>column</firstterm>
     is either a user-defined column of a given table or one of the
     following system-defined columns:

     <variablelist>
      <varlistentry>
       <term>oid</term>
       <listitem>
	<para>
	 The unique identifier (object ID) of a row.  This is a serial number
	 that is added by Postgres to all rows automatically. OIDs are not
	 reused and are 32-bit quantities.
	</para>
       </listitem>
      </varlistentry>

      <varlistentry>
      <term>tableoid</term>
       <listitem>
	<para>
	 The OID of the table containing this row.  This attribute is
	 particularly handy for queries that select from inheritance
	 hierarchies, since without it, it's difficult to tell which
	 individual table a row came from.  The tableoid can be joined
	 against the OID attribute of pg_class to obtain the table name.
	</para>
       </listitem>
      </varlistentry>

      <varlistentry>
       <term>xmin</term>
       <listitem>
	<para>
	 The identity (transaction ID) of the inserting transaction for
	 this tuple.  (Note: a tuple is an individual state of a row;
	 each UPDATE of a row creates a new tuple for the same logical row.)
	</para>
       </listitem>
      </varlistentry>

      <varlistentry>
      <term>cmin</term>
       <listitem>
	<para>
	 The command identifier (starting at zero) within the inserting
	 transaction.
	</para>
       </listitem>
      </varlistentry>

      <varlistentry>
      <term>xmax</term>
       <listitem>
	<para>
	 The identity (transaction ID) of the deleting transaction,
	 or zero for an undeleted tuple.  In practice, this is never nonzero
	 for a visible tuple.
	</para>
       </listitem>
      </varlistentry>

      <varlistentry>
      <term>cmax</term>
       <listitem>
	<para>
	 The command identifier within the deleting transaction, or zero.
	 Again, this is never nonzero for a visible tuple.
	</para>
       </listitem>
      </varlistentry>

      <varlistentry>
      <term>ctid</term>
       <listitem>
	<para>
	 The tuple ID of the tuple within its table.  This is a pair
	 (block number, tuple index within block) that identifies the
	 physical location of the tuple.  Note that although the ctid
	 can be used to locate the tuple very quickly, a row's ctid
	 will change each time it is updated or moved by VACUUM.
	 Therefore ctid is useless as a long-term row identifier.
	 The OID, or even better a user-defined serial number, should
	 be used to identify logical rows.
	</para>
       </listitem>
      </varlistentry>
     </variablelist>
    </para>

    <para>
     For further information on the system attributes consult
     <xref linkend="STON87a" endterm="STON87a">.
     Transaction and command identifiers are 32 bit quantities.
    </para>

  </sect1>


 <sect1 id="sql-expressions">
  <title>Value Expressions</title>

  <para>
   Value expressions are used in a variety of syntactic contexts, such
   as in the target list of the <command>SELECT</command> command, as
   new column values in <command>INSERT</command> or
   <command>UPDATE</command>, or in search conditions in a number of
   commands.  The result of a value expression is sometimes called a
   <firstterm>scalar</firstterm>, to distinguish it from the result of
   a table expression (which is a table).  Value expressions are
   therefore also called <firstterm>scalar expressions</firstterm> (or
   even simply <firstterm>expressions</firstterm>).  The expression
   syntax allows the calculation of values from primitive parts using
   arithmetic, logical, set, and other operations.
  </para>

  <para>
   A value expression is one of the following:

   <itemizedlist>
    <listitem>
     <para>
      A constant or literal value; see <xref linkend="sql-syntax-constants">.
     </para>
    </listitem>

    <listitem>
     <para>
      A column reference
     </para>
    </listitem>

    <listitem>
     <para>
      An operator invocation:
      <simplelist>
       <member><replaceable>expression</replaceable> <replaceable>operator</replaceable> <replaceable>expression</replaceable> (binary infix operator)</member>
       <member><replaceable>expression</replaceable> <replaceable>operator</replaceable> (unary postfix operator)</member>
       <member><replaceable>operator</replaceable> <replaceable>expression</replaceable> (unary prefix operator)</member>
      </simplelist>
      where <replaceable>operator</replaceable> follows the syntax
      rules of <xref linkend="sql-syntax-operators"> or is one of the
      tokens <token>AND</token>, <token>OR</token>, and
      <token>NOT</token>.  What particular operators exist and whether
      they are unary or binary depends on what operators have been
      defined by the system or the user.  <xref linkend="functions">
      describes the built-in operators.
     </para>
    </listitem>

    <listitem>
     <para>
<synopsis>( <replaceable>expression</replaceable> )</synopsis>
      Parentheses are used to group subexpressions and override precedence.
     </para>
    </listitem>

    <listitem>
     <para>
      A positional parameter reference, in the body of a function declaration.
     </para>
    </listitem>

    <listitem>
     <para>
      A function call
     </para>
    </listitem>

    <listitem>
     <para>
      An aggregate expression
     </para>
    </listitem>

    <listitem>
     <para>
      A scalar subquery.  This is an ordinary
      <command>SELECT</command> in parenthesis that returns exactly one
      row with one column.  It is an error to use a subquery that
      returns more than one row or more than one column in the context
      of a value expression.
     </para>
    </listitem>
   </itemizedlist>
  </para>

  <para>
   In addition to this list, there are a number of contructs that can
   be classified as an expression but do not follow any general syntax
   rules.  These generally have the semantics of a function or
   operator and are explained in the appropriate location in <xref
   linkend="functions">.  An example is the <literal>IS NULL</literal>
   clause.
  </para>

  <para>
   We have already discussed constants in <xref
   linkend="sql-syntax-constants">.  The following sections discuss
   the remaining options.
  </para>

  <sect2>
   <title>Column References</title>

   <para>
    A column can be referenced in the form:
<synopsis>
<replaceable>corelation</replaceable>.<replaceable>columnname</replaceable> `['<replaceable>subscript</replaceable>`]'
</synopsis>

    <replaceable>corelation</replaceable> is either the name of a
    table, an alias for a table defined by means of a FROM clause, or
    the keyword <literal>NEW</literal> or <literal>OLD</literal>.
    (NEW and OLD can only appear in the action portion of a rule,
    while other corelation names can be used in any SQL statement.)
    The corelation name can be omitted if the column name is unique
    across all the tables being used in the current query.  If
    <replaceable>column</replaceable> is of an array type, then the
    optional <replaceable>subscript</replaceable> selects a specific
    element in the array.  If no subscript is provided, then the whole
    array is selected.  Refer to the description of the particular
    commands in the <citetitle>PostgreSQL Reference Manual</citetitle>
    for the allowed syntax in each case.
   </para>
  </sect2>

  <sect2>
   <title>Positional Parameters</title>

   <para>
    A positional parameter reference is used to indicate a parameter
    in an SQL function.  Typically this is used in SQL function
    definition statements.  The form of a parameter is:
<synopsis>
$<replaceable>number</replaceable>
</synopsis>
   </para>

   <para>
    For example, consider the definition of a function,
    <function>dept</function>, as

<programlisting>
CREATE FUNCTION dept (text) RETURNS dept
  AS 'select * from dept where name = $1'
  LANGUAGE 'sql';
</programlisting>

    Here the <literal>$1</literal> will be replaced by the first
    function argument when the function is invoked.
   </para>
  </sect2>

  <sect2>
   <title>Function Calls</title>

   <para>
    The syntax for a function call is the name of a legal function
    (subject to the syntax rules for identifiers of <xref
    linkend="sql-syntax-identifiers"> , followed by its argument list
    enclosed in parentheses:

<synopsis>
<replaceable>function</replaceable> (<optional><replaceable>expression</replaceable> <optional>, <replaceable>expression</replaceable> ... </optional></optional> )
</synopsis>
   </para>

   <para>
    For example, the following computes the square root of 2:
<programlisting>
sqrt(2)
</programlisting>
   </para>

   <para>
    The list of built-in functions is in <xref linkend="functions">.
    Other functions may be added by the user.
   </para>
  </sect2>

  <sect2 id="syntax-aggregates">
   <title>Aggregate Expressions</title>

   <para>
    An <firstterm>aggregate expression</firstterm> represents the
    application of an aggregate function across the rows selected by a
    query.  An aggregate function reduces multiple inputs to a single
    output value, such as the sum or average of the inputs.  The
    syntax of an aggregate expression is one of the following:

    <simplelist>
     <member><replaceable>aggregate_name</replaceable> (<replaceable>expression</replaceable>)</member>
     <member><replaceable>aggregate_name</replaceable> (ALL <replaceable>expression</replaceable>)</member>
     <member><replaceable>aggregate_name</replaceable> (DISTINCT <replaceable>expression</replaceable>)</member>
     <member><replaceable>aggregate_name</replaceable> ( * )</member>
    </simplelist>

    where <replaceable>aggregate_name</replaceable> is a previously
    defined aggregate, and <replaceable>expression</replaceable> is
    any expression that does not itself contain an aggregate
    expression.
   </para>

   <para>
    The first form of aggregate expression invokes the aggregate
    across all input rows for which the given expression yields a
    non-NULL value.  The second form is the same as the first, since
    <literal>ALL</literal> is the default.  The third form invokes the
    aggregate for all distinct non-NULL values of the expression found
    in the input rows.  The last form invokes the aggregate once for
    each input row regardless of NULL or non-NULL values; since no
    particular input value is specified, it is generally only useful
    for the <function>count()</function> aggregate function.
   </para>

   <para>
    For example, <literal>count(*)</literal> yields the total number
    of input rows; <literal>count(f1)</literal> yields the number of
    input rows in which <literal>f1</literal> is non-NULL;
    <literal>count(distinct f1)</literal> yields the number of
    distinct non-NULL values of <literal>f1</literal>.
   </para>

   <para>
    The predefined aggregate functions are described in <xref
    linkend="functions-aggregate">.
   </para>
  </sect2>

 </sect1>


  <sect1 id="sql-precedence">
   <title>Lexical Precedence</title>

   <para>
    The precedence and associativity of the operators is hard-wired
    into the parser.  Most operators have the same precedence and are
    left-associative.  This may lead to non-intuitive behavior; for
    example the boolean operators "&lt;" and "&gt;" have a different
    precedence than the boolean operators "&lt;=" and "&gt;=".  Also,
    you will sometimes need to add parentheses when using combinations
    of binary and unary operators.  For instance
<programlisting>
SELECT 5 &amp; ~ 6;
</programlisting>
   will be parsed as
<programlisting>
SELECT (5 &amp;) ~ 6;
</programlisting>
    because the parser has no idea that <token>&amp;</token> is
    defined as a binary operator.  This is the price one pays for
    extensibility.
   </para>

   <table tocentry="1">
    <title>Operator Precedence (decreasing)</title>

    <tgroup cols="2">
     <thead>
      <row>
       <entry>OperatorElement</entry>
       <entry>Associativity</entry>
       <entry>Description</entry>
      </row>
     </thead>

     <tbody>
      <row>
       <entry><token>::</token></entry>
       <entry>left</entry>
       <entry><productname>Postgres</productname>-style typecast</entry>
      </row>

      <row>
       <entry><token>[</token> <token>]</token></entry>
       <entry>left</entry>
       <entry>array element selection</entry>
      </row>

      <row>
       <entry><token>.</token></entry>
       <entry>left</entry>
       <entry>table/column name separator</entry>
      </row>

      <row>
       <entry><token>-</token></entry>
       <entry>right</entry>
       <entry>unary minus</entry>
      </row>

      <row>
       <entry><token>^</token></entry>
       <entry>left</entry>
       <entry>exponentiation</entry>
      </row>

      <row>
       <entry><token>*</token> <token>/</token> <token>%</token></entry>
       <entry>left</entry>
       <entry>multiplication, division, modulo</entry>
      </row>

      <row>
       <entry><token>+</token> <token>-</token></entry>
       <entry>left</entry>
       <entry>addition, subtraction</entry>
      </row>

      <row>
       <entry><token>IS</token></entry>
       <entry></entry>
       <entry>test for TRUE, FALSE, NULL</entry>
      </row>

      <row>
       <entry><token>ISNULL</token></entry>
       <entry></entry>
       <entry>test for NULL</entry>
      </row>

      <row>
       <entry><token>NOTNULL</token></entry>
       <entry></entry>
       <entry>test for NOT NULL</entry>
      </row>

      <row>
       <entry>(any other)</entry>
       <entry>left</entry>
       <entry>all other native and user-defined operators</entry>
      </row>

      <row>
       <entry><token>IN</token></entry>
       <entry></entry>
       <entry>set membership</entry>
      </row>

      <row>
       <entry><token>BETWEEN</token></entry>
       <entry></entry>
       <entry>containment</entry>
      </row>

      <row>
       <entry><token>OVERLAPS</token></entry>
       <entry></entry>
       <entry>time interval overlap</entry>
      </row>

      <row>
       <entry><token>LIKE</token> <token>ILIKE</token></entry>
       <entry></entry>
       <entry>string pattern matching</entry>
      </row>

      <row>
       <entry><token>&lt;</token> <token>&gt;</token></entry>
       <entry></entry>
       <entry>less than, greater than</entry>
      </row>

      <row>
       <entry><token>=</token></entry>
       <entry>right</entry>
       <entry>equality, assignment</entry>
      </row>

      <row>
       <entry><token>NOT</token></entry>
       <entry>right</entry>
       <entry>logical negation</entry>
      </row>

      <row>
       <entry><token>AND</token></entry>
       <entry>left</entry>
       <entry>logical conjunction</entry>
      </row>

      <row>
       <entry><token>OR</token></entry>
       <entry>left</entry>
       <entry>logical disjunction</entry>
      </row>
     </tbody>
    </tgroup>
   </table>

   <para>
    Note that the operator precedence rules also apply to user-defined
    operators that have the same names as the built-in operators
    mentioned above.  For example, if you define a
    <quote>+</quote> operator for some custom data type it will have
    the same precedence as the built-in <quote>+</quote> operator, no
    matter what yours does.
   </para>
  </sect1>


 <sect1 id="sql-table-expressions">
  <title>Table Expressions</title>

  <para>
   A <firstterm>table expression</firstterm> specifies a table.  The
   table expression contains a FROM clause that is optionally followed
   by WHERE, GROUP BY, and HAVING clauses.  Trivial table expressions
   simply refer to a table on disk, a so-called base table, but more
   complex expressions can be used to modify or combine base tables in
   various ways.
  </para>

  <para>
   The general syntax of the <command>SELECT</command> command is
<synopsis>
SELECT <replaceable>select_list</replaceable> <replaceable>table_expression</replaceable>
</synopsis>

   The <replaceable>select_list</replaceable> is a comma separated
   list of <replaceable>value expressions</replaceable> as defined in
   <xref linkend="sql-expressions"> that specify the derived columns
   of the query output table.  Column names in the derived table that
   is the result of the <replaceable>table_expression</replaceable>
   can be used in the <replaceable>value expression</replaceable>s of
   the <replaceable>select_list</replaceable>.
  </para>

  <para>
   The WHERE, GROUP BY, and HAVING clauses in the table expression
   specify a pipeline of successive transformations performed on the
   table derived in the FROM clause.  The final transformed table that
   is derived provides the input rows used to derive output rows as
   specified by the select list of derived column value expressions.
  </para>
	
  <sect2>
   <title>FROM clause</title>
 
   <para>
    The FROM clause derives a table from one or more other tables
    given in a comma-separated table reference list.
<synopsis>
FROM <replaceable>table_reference</replaceable> <optional>, <replaceable>table_reference</replaceable> <optional>, ...</optional></optional>
</synopsis>

    A table reference may be a table name or a derived table such as a
    subquery, a table join, or complex combinations of these.  If more
    than one table reference is listed in the FROM clause they are
    CROSS JOINed (see below) to form the derived table that may then
    be subject to transformations by the WHERE, GROUP BY, and HAVING
    clauses and is finally the result of the overall table expression.
   </para>

   <para>
    If a table reference is a simple table name and it is the
    supertable in a table inheritance hierarchy, rows of the table
    include rows from all of its subtable successors unless the
    keyword ONLY precedes the table name.
   </para>

   <sect3>
    <title>Joined Tables</title>

    <para>
     A joined table is a table derived from two other (real or
     derived) tables according to the rules of the particular join
     type.  INNER, OUTER, NATURAL, and CROSS JOIN are supported.
    </para>

    <variablelist>
     <title>Join Types</title>

     <varlistentry>
      <term>CROSS JOIN</term>

      <listitem>
<synopsis>
<replaceable>T1</replaceable> CROSS JOIN <replaceable>T2</replaceable>
</synopsis>

       <para>
        For each combination of rows from
        <replaceable>T1</replaceable> and
        <replaceable>T2</replaceable> the derived table will contain a
        row consisting of all columns in <replaceable>T1</replaceable>
        followed by all columns in <replaceable>T2</replaceable>.  If
        the tables have have N and M rows respectively, the joined
        table will have N * M rows.  A cross join is essentially an
        <literal>INNER JOIN ON TRUE</literal>.
       </para>

       <tip>
        <para>
         <literal>FROM <replaceable>T1</replaceable> CROSS JOIN
         <replaceable>T2</replaceable></literal> is equivalent to
         <literal>FROM <replaceable>T1</replaceable>,
         <replaceable>T2</replaceable></literal>.
        </para>
       </tip>
      </listitem>
     </varlistentry>

     <varlistentry>
      <term>Qualified JOINs</term>
      <listitem>

<synopsis>
<replaceable>T1</replaceable> { <optional>INNER</optional> | { LEFT | RIGHT | FULL } <optional>OUTER</optional> } JOIN <replaceable>T2</replaceable> ON <replaceable>boolean expression</replaceable>
<replaceable>T1</replaceable> { <optional>INNER</optional> | { LEFT | RIGHT | FULL } <optional>OUTER</optional> } JOIN <replaceable>T2</replaceable> USING ( <replaceable>join column list</replaceable> )
</synopsis>
        
       <para>
        The words <token>INNER</token> and <token>OUTER</token> are
        optional for all JOINs.  <token>INNER</token> is the default;
        <token>LEFT</token>, <token>RIGHT</token>, and
        <token>FULL</token> are for OUTER JOINs only.
       </para>

       <para>
        The <firstterm>join condition</firstterm> is specified in the
        ON or USING clause.  (The meaning of the join condition
        depends on the particular join type; see below.)  The ON
        clause takes a boolean value expression of the same kind as is
        used in a WHERE clause.  The USING clause takes a
        comma-separated list of column names, which the joined tables
        must have in common, and joins the tables on the equality of
        those columns as a set, resulting in a joined table having one
        column for each common column listed and all of the other
        columns from both tables.  Thus, <literal>USING (a, b,
        c)</literal> is equivalent to <literal>ON (t1.a = t2.a AND
        t1.b = t2.b AND t1.c = t2.c)</literal> with the exception that
        if ON is used there will be two columns a, b, and c in the
        result, whereas with USING there will be only one of each.
       </para>

       <variablelist>
        <varlistentry>
         <term>INNER JOIN</term>

         <listitem>
          <para>
           For each row R1 of T1, the joined table has a row for each
           row in T2 that satisfies the join condition with R1.
          </para>
         </listitem>
        </varlistentry>

        <varlistentry>
         <term>LEFT OUTER JOIN</term>

         <listitem>
          <para>
           First, an INNER JOIN is performed.  Then, for a row in T1
           that does not satisfy the join condition with any row in
           T2, a joined row is returned with NULL values in columns of
           T2.  Thus, the joined table unconditionally has a row for each
           row in T1.
          </para>
         </listitem>
        </varlistentry>
         
        <varlistentry>
         <term>RIGHT OUTER JOIN</term>

         <listitem>
          <para>
           This is like a left join, only that the result table will
           unconditionally have a row for each row in T2.
          </para>
         </listitem>
        </varlistentry>
         
        <varlistentry>
         <term>FULL OUTER JOIN</term>

         <listitem>
          <para>
           First, an INNER JOIN is performed.  Then, for each row in
           T1 that does not satisfy the join condition with any row in
           T2, a joined row is returned with null values in columns of
           T2.  Also, for each row of T2 that does not satisfy the
           join condition with any row in T1, a joined row with null
           values in the columns of T1 is returned.
          </para>
         </listitem>
        </varlistentry>
       </variablelist>
      </listitem>
     </varlistentry>
      
     <varlistentry>
      <term>NATURAL JOIN</term>

      <listitem>
<synopsis>
<replaceable>T1</replaceable> NATURAL { <optional>INNER</optional> | { LEFT | RIGHT | FULL } <optional>OUTER</optional> JOIN <replaceable>T2</replaceable>
</synopsis>
       <para>
        A natural join creates a joined table where every pair of matching
        column names between the two tables are merged into one column. The
        join specification is effectively a USING clause containing all the
        common column names and is otherwise like a Qualified JOIN.
       </para>
      </listitem>
     </varlistentry>
    </variablelist>

    <para>
     Joins of all types can be chained together or nested where either
     or both of <replaceable>T1</replaceable> and
     <replaceable>T2</replaceable> may be JOINed tables.  Parenthesis
     can be used around JOIN clauses to control the join order which
     are otherwise left to right.
    </para>
   </sect3>

   <sect3 id="sql-subqueries">
    <title>Subqueries</title>

    <para>
     Subqueries specifying a derived table must be enclosed in
     parenthesis and <emphasis>must</emphasis> be named using an AS
     clause.  (See <xref linkend="sql-table-aliases">.)
    </para>

<programlisting>
FROM (SELECT * FROM table1) AS alias_name
</programlisting>

    <para>
     This example is equivalent to <literal>FROM table1 AS
     alias_name</literal>.  Many subquieries can be written as table
     joins instead.
    </para>
   </sect3>

   <sect3 id="sql-table-aliases">
    <title>Table and Column Aliases</title>

    <para>
     A temporary name can be given to tables and complex table
     references to be used for references to the derived table in
     further processing.  This is called a <firstterm>table
     alias</firstterm>.
<synopsis>
FROM <replaceable>table_reference</replaceable> AS <replaceable>alias</replaceable>
</synopsis>
     Here, <replaceable>alias</replaceable> can be any regular
     identifier.  The alias becomes the new name of the table
     reference for the current query -- it is no longer possible to
     refer to the table by the original name (if the table reference
     was an ordinary base table).  Thus
<programlisting>
SELECT * FROM my_table AS m WHERE my_table.a > 5;
</programlisting>
     is not valid SQL syntax.  What will happen instead, as a
     <productname>Postgres</productname> extension, is that an implict
     table reference is added to the FROM clause, so the query is
     processed as if it was written as
<programlisting>
SELECT * FROM my_table AS m, my_table WHERE my_table.a > 5;
</programlisting>
     Table aliases are mainly for notational convenience, but it is
     necessary to use them when joining a table to itself, e.g.,
<programlisting>
SELECT * FROM my_table AS a CROSS JOIN my_table AS b ...
</programlisting>
     Additionally, an alias is required if the table reference is a
     subquery.
    </para>

    <para>
     Parenthesis are used to resolve ambiguities.  The following
     statement will assign the alias <literal>b</literal> to the
     result of the join, unlike the previous example:
<programlisting>
SELECT * FROM (my_table AS a CROSS JOIN my_table) AS b ...
</programlisting>
    </para>

    <para>
<synopsis>
FROM <replaceable>table_reference</replaceable> <replaceable>alias</replaceable>
</synopsis>
     This form is equivalent the previously treated one; the
     <token>AS</token> key word is noise.
    </para>

    <para>
<synopsis>
FROM <replaceable>table_reference</replaceable> <optional>AS</optional> <replaceable>alias</replaceable> ( <replaceable>column1</replaceable> <optional>, <replaceable>column2</replaceable> <optional>, ...</optional></optional> )
</synopsis>
     In addition to renaming the table as described above, the columns
     of the table are also given temporary names.  If less column
     aliases are specified than the actual table has columns, the last
     columns are not renamed.  This syntax is especially useful for
     self-joins or subqueries.
    </para>
   </sect3>

   <sect3>
    <title>Examples</title>

    <para>
<programlisting>
FROM T1 INNER JOIN T2 USING (C)
FROM T1 LEFT OUTER JOIN T2 USING (C)
FROM (T1 RIGHT OUTER JOIN T2 ON (T1C1=T2C1)) AS DT1
FROM (T1 FULL OUTER JOIN T2 USING (C)) AS DT1 (DT1C1, DT1C2)

FROM T1 NATURAL INNER JOIN T2
FROM T1 NATURAL LEFT OUTER JOIN T2
FROM T1 NATURAL RIGHT OUTER JOIN T2
FROM T1 NATURAL FULL OUTER JOIN T2

FROM (SELECT * FROM T1) DT1 CROSS JOIN T2, T3
FROM (SELECT * FROM T1) DT1, T2, T3
</programlisting>

     Above are some examples of joined tables and complex derived
     tables.  Notice how the AS clause renames or names a derived
     table and how the optional comma-separated list of column names
     that follows gives names or renames the columns.  The last two
     FROM clauses produce the same derived table from T1, T2, and T3.
     The AS keyword was omitted in naming the subquery as DT1.  The
     keywords OUTER and INNER are noise that can be omitted also.
    </para>
   </sect3>

  </sect2>

  <sect2>
   <title>WHERE clause</title>

   <para>
    The syntax of the WHERE clause is
<synopsis>
WHERE <replaceable>search condition</replaceable>
</synopsis>
    where <replaceable>search condition</replaceable> is any value
    expression as defined in <xref linkend="sql-expressions"> that
    returns a value of type <type>boolean</type>.
   </para>

   <para>
    After the processing of the FROM clause is done, each row of the
    derived table is checked against the search condition.  If the
    result of the condition is true, the row is kept in the output
    table, otherwise (that is, if the result is false or NULL) it is
    discared.  The search condition typically references at least some
    column in the table generated in the FROM clause; this is not
    required, but otherwise the WHERE clause will be fairly useless.
   </para>

   <note>
    <para>
     Before the implementation of the JOIN syntax, it was necessary to
     put the join condition of an inner join in the WHERE clause.  For
     example, these table expressions are equivalent:
<programlisting>
FROM a, b WHERE a.id = b.id AND b.val &gt; 5
</programlisting>
     and
<programlisting>
FROM a INNER JOIN b ON (a.id = b.id) WHERE b.val &gt; 5
</programlisting>
     or perhaps even
<programlisting>
FROM a NATURAL JOIN b WHERE b.val &gt; 5
</programlisting>
     Which one of these you use is mainly a matter of style.  The JOIN
     syntax in the FROM clause is probably not as portable to other
     products.  For outer joins there is no choice in any case:  they
     must be done in the FROM clause.
    </para>
   </note>

<programlisting>
FROM FDT WHERE
    C1 > 5

FROM FDT WHERE
    C1 IN (1, 2, 3)
FROM FDT WHERE
    C1 IN (SELECT C1 FROM T2)
FROM FDT WHERE
    C1 IN (SELECT C3 FROM T2 WHERE C2 = FDT.C1 + 10)

FROM FDT WHERE
    C1 BETWEEN (SELECT C3 FROM T2 WHERE C2 = FDT.C1 + 10) AND 100

FROM FDT WHERE
    EXISTS (SELECT C1 FROM T2 WHERE C2 > FDT.C1)
</programlisting>

   <para>
    In the examples above, FDT is the table derived in the FROM
    clause. Rows that do not meet the search condition of the where
    clause are eliminated from FDT. Notice the use of scalar
    subqueries as value expressions (C2 assumed UNIQUE).  Just like
    any other query, the subqueries can employ complex table
    expressions.  Notice how FDT is referenced in the subqueries.
    Qualifying C1 as FDT.C1 is only necessary if C1 is the name of a
    column in the derived input table of the subquery.  Qualifying the
    column name adds clarity even when it is not needed.  The column
    naming scope of an outer query extends into its inner queries.
   </para>
  </sect2>

<!-- This is confusing as heck.  Make it simpler. -->

<![IGNORE[

  <sect2>
   <title>GROUP BY and HAVING clauses</title>	   

   <para>
    After passing the WHERE filter, the derived input table may be
    subject to grouping, using the GROUP BY clause, and elimination of
    group rows using the HAVING clause.  (The HAVING clause can also
    be used without GROUP BY, but then it is equivalent to the WHERE
    clause.)
   </para>

   <para>
    In standard SQL, the GROUP BY clause takes a list of column names,
    that specify a subrow, from the derived input table produced by
    the previous WHERE or FROM clause and partitions the table into
    groups with duplicate subrows such that within a column of the
    subrow, no column value is distinct from other column values. The
    resulting derived input table is a special type of table, called a
    grouped table, which still contains all columns but only
    references to columns of the grouped subrow, and group aggregates,
    derived from any of the columns, may appear in derived column
    value expressions in the query select list.  When deriving an
    output table from a query using a grouped input table, each output
    row is derived from a corresponding group/partition of the grouped
    table. Aggregates computed in a derived output column are
    aggregates on the current partition/group of the grouped input
    table being processed.  Only one output table row results per
    group/partition of the grouped input table.
   </para>

   <para>
    Postgres has extended the GROUP BY clause to allow some
    non-standard, but useful behavior. Derived output columns, given
    names using an AS clause in the query select list, may appear in
    the GROUP BY clause in combination with, or instead of, the input
    table column names. Tables may also be grouped by arbitrary
    expressions. If output table column names appear in the GROUP BY
    list, then the input table is augmented with additional columns of
    the output table columns listed in the GROUP BY clause. The value
    for each row in the additional columns is computed from the value
    expression that defines the output column in the query select
    list. The augmented input table is grouped by the column names
    listed in the GROUP BY clause. The resulting grouped augmented
    input table is then treated according standard SQL GROUP BY
    semantics. Only the columns of the unaugmented input table in the
    grouped subrow (if any), and group aggregates, derived from any of
    the columns of the unaugmented input table, may be referenced in
    the value expressions of the derived output columns of the
    query. Output columns derived with an aggregate expression cannot
    be named in the GROUP BY clause.
   </para>

   <para>
    A HAVING clause may optionally follow a GROUP BY clause.  The
    HAVING clause selects or eliminates, depending on which
    perspective is taken, groups from the grouped table derived in the
    GROUP BY clause that precedes it.  The search condition is the
    same type of expression allowed in a WHERE clause and may
    reference any of the input table column names in the grouped
    subrow, but may not reference any others or any named output
    columns.  When the search condition results in TRUE the group is
    retained, otherwise the group is eliminated.
   </para>
  </sect2>

   <sect2>
    <title>ORDER BY and LIMIT clauses</title>
	   
    <para>
     ORDER BY and LIMIT clauses are not clauses of a table expression.
     They are optional clauses that may follow a query expression and
     are discussed here because they are commonly used with the
     clauses above.
    </para>

    <para>
     ORDER BY takes a comma-separated list of columns and performs a
     cascaded ordering of the table by the columns listed, in the
     order listed.  The keyword DESC or ASC may follow any column name
     or expression in the list to specify descending or ascending
     ordering, respectively. Ascending order is the default.  The
     ORDER BY clause conforms to the SQL standard but is extended in
     Postgres.  Postgres allows ORDER BY to reference both output
     table columns, as named in the select list using the AS clause,
     and input table columns, as given by the table derived in the
     FROM clause and other previous clauses. Postgres also extends
     ORDER BY to allow ordering by arbitrary expressions. If used in a
     query with a GROUP BY clause, the ORDER BY clause can only
     reference output table column names and grouped input table
     columns.
    </para>

    <para>
     LIMIT is not a standard SQL clause.  LIMIT is a Postgres
     extension that limits the number of rows that will be returned
     from a query.  The rows returned by a query using the LIMIT
     clause are random if no ORDER BY clause is specified.  A LIMIT
     clause may optionally be followed by an OFFSET clause which
     specifies a number of rows to be skipped in the output table
     before returning the number of rows specified in the LIMIT
     clause.
    </para>
   </sect2>
]]>
  </sect1>

</chapter>

<!-- Keep this comment at the end of the file
Local variables:
mode:sgml
sgml-omittag:nil
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
sgml-parent-document:nil
sgml-default-dtd-file:"./reference.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:("/usr/lib/sgml/catalog")
sgml-local-ecat-files:nil
End:
-->