]> begriffs open source - ai-pg/blob - full-docs/txt/sql-syntax-lexical.txt
Convert HTML docs to more streamlined TXT
[ai-pg] / full-docs / txt / sql-syntax-lexical.txt
1
2 4.1. Lexical Structure #
3
4    4.1.1. Identifiers and Key Words
5    4.1.2. Constants
6    4.1.3. Operators
7    4.1.4. Special Characters
8    4.1.5. Comments
9    4.1.6. Operator Precedence
10
11    SQL input consists of a sequence of commands. A command is composed of
12    a sequence of tokens, terminated by a semicolon (“;”). The end of the
13    input stream also terminates a command. Which tokens are valid depends
14    on the syntax of the particular command.
15
16    A token can be a key word, an identifier, a quoted identifier, a
17    literal (or constant), or a special character symbol. Tokens are
18    normally separated by whitespace (space, tab, newline), but need not be
19    if there is no ambiguity (which is generally only the case if a special
20    character is adjacent to some other token type).
21
22    For example, the following is (syntactically) valid SQL input:
23 SELECT * FROM MY_TABLE;
24 UPDATE MY_TABLE SET A = 5;
25 INSERT INTO MY_TABLE VALUES (3, 'hi there');
26
27    This is a sequence of three commands, one per line (although this is
28    not required; more than one command can be on a line, and commands can
29    usefully be split across lines).
30
31    Additionally, comments can occur in SQL input. They are not tokens,
32    they are effectively equivalent to whitespace.
33
34    The SQL syntax is not very consistent regarding what tokens identify
35    commands and which are operands or parameters. The first few tokens are
36    generally the command name, so in the above example we would usually
37    speak of a “SELECT”, an “UPDATE”, and an “INSERT” command. But for
38    instance the UPDATE command always requires a SET token to appear in a
39    certain position, and this particular variation of INSERT also requires
40    a VALUES in order to be complete. The precise syntax rules for each
41    command are described in Part VI.
42
43 4.1.1. Identifiers and Key Words #
44
45    Tokens such as SELECT, UPDATE, or VALUES in the example above are
46    examples of key words, that is, words that have a fixed meaning in the
47    SQL language. The tokens MY_TABLE and A are examples of identifiers.
48    They identify names of tables, columns, or other database objects,
49    depending on the command they are used in. Therefore they are sometimes
50    simply called “names”. Key words and identifiers have the same lexical
51    structure, meaning that one cannot know whether a token is an
52    identifier or a key word without knowing the language. A complete list
53    of key words can be found in Appendix C.
54
55    SQL identifiers and key words must begin with a letter (a-z, but also
56    letters with diacritical marks and non-Latin letters) or an underscore
57    (_). Subsequent characters in an identifier or key word can be letters,
58    underscores, digits (0-9), or dollar signs ($). Note that dollar signs
59    are not allowed in identifiers according to the letter of the SQL
60    standard, so their use might render applications less portable. The SQL
61    standard will not define a key word that contains digits or starts or
62    ends with an underscore, so identifiers of this form are safe against
63    possible conflict with future extensions of the standard.
64
65    The system uses no more than NAMEDATALEN-1 bytes of an identifier;
66    longer names can be written in commands, but they will be truncated. By
67    default, NAMEDATALEN is 64 so the maximum identifier length is 63
68    bytes. If this limit is problematic, it can be raised by changing the
69    NAMEDATALEN constant in src/include/pg_config_manual.h.
70
71    Key words and unquoted identifiers are case-insensitive. Therefore:
72 UPDATE MY_TABLE SET A = 5;
73
74    can equivalently be written as:
75 uPDaTE my_TabLE SeT a = 5;
76
77    A convention often used is to write key words in upper case and names
78    in lower case, e.g.:
79 UPDATE my_table SET a = 5;
80
81    There is a second kind of identifier: the delimited identifier or
82    quoted identifier. It is formed by enclosing an arbitrary sequence of
83    characters in double-quotes ("). A delimited identifier is always an
84    identifier, never a key word. So "select" could be used to refer to a
85    column or table named “select”, whereas an unquoted select would be
86    taken as a key word and would therefore provoke a parse error when used
87    where a table or column name is expected. The example can be written
88    with quoted identifiers like this:
89 UPDATE "my_table" SET "a" = 5;
90
91    Quoted identifiers can contain any character, except the character with
92    code zero. (To include a double quote, write two double quotes.) This
93    allows constructing table or column names that would otherwise not be
94    possible, such as ones containing spaces or ampersands. The length
95    limitation still applies.
96
97    Quoting an identifier also makes it case-sensitive, whereas unquoted
98    names are always folded to lower case. For example, the identifiers
99    FOO, foo, and "foo" are considered the same by PostgreSQL, but "Foo"
100    and "FOO" are different from these three and each other. (The folding
101    of unquoted names to lower case in PostgreSQL is incompatible with the
102    SQL standard, which says that unquoted names should be folded to upper
103    case. Thus, foo should be equivalent to "FOO" not "foo" according to
104    the standard. If you want to write portable applications you are
105    advised to always quote a particular name or never quote it.)
106
107    A variant of quoted identifiers allows including escaped Unicode
108    characters identified by their code points. This variant starts with U&
109    (upper or lower case U followed by ampersand) immediately before the
110    opening double quote, without any spaces in between, for example
111    U&"foo". (Note that this creates an ambiguity with the operator &. Use
112    spaces around the operator to avoid this problem.) Inside the quotes,
113    Unicode characters can be specified in escaped form by writing a
114    backslash followed by the four-digit hexadecimal code point number or
115    alternatively a backslash followed by a plus sign followed by a
116    six-digit hexadecimal code point number. For example, the identifier
117    "data" could be written as
118 U&"d\0061t\+000061"
119
120    The following less trivial example writes the Russian word “slon”
121    (elephant) in Cyrillic letters:
122 U&"\0441\043B\043E\043D"
123
124    If a different escape character than backslash is desired, it can be
125    specified using the UESCAPE clause after the string, for example:
126 U&"d!0061t!+000061" UESCAPE '!'
127
128    The escape character can be any single character other than a
129    hexadecimal digit, the plus sign, a single quote, a double quote, or a
130    whitespace character. Note that the escape character is written in
131    single quotes, not double quotes, after UESCAPE.
132
133    To include the escape character in the identifier literally, write it
134    twice.
135
136    Either the 4-digit or the 6-digit escape form can be used to specify
137    UTF-16 surrogate pairs to compose characters with code points larger
138    than U+FFFF, although the availability of the 6-digit form technically
139    makes this unnecessary. (Surrogate pairs are not stored directly, but
140    are combined into a single code point.)
141
142    If the server encoding is not UTF-8, the Unicode code point identified
143    by one of these escape sequences is converted to the actual server
144    encoding; an error is reported if that's not possible.
145
146 4.1.2. Constants #
147
148    There are three kinds of implicitly-typed constants in PostgreSQL:
149    strings, bit strings, and numbers. Constants can also be specified with
150    explicit types, which can enable more accurate representation and more
151    efficient handling by the system. These alternatives are discussed in
152    the following subsections.
153
154 4.1.2.1. String Constants #
155
156    A string constant in SQL is an arbitrary sequence of characters bounded
157    by single quotes ('), for example 'This is a string'. To include a
158    single-quote character within a string constant, write two adjacent
159    single quotes, e.g., 'Dianne''s horse'. Note that this is not the same
160    as a double-quote character (").
161
162    Two string constants that are only separated by whitespace with at
163    least one newline are concatenated and effectively treated as if the
164    string had been written as one constant. For example:
165 SELECT 'foo'
166 'bar';
167
168    is equivalent to:
169 SELECT 'foobar';
170
171    but:
172 SELECT 'foo'      'bar';
173
174    is not valid syntax. (This slightly bizarre behavior is specified by
175    SQL; PostgreSQL is following the standard.)
176
177 4.1.2.2. String Constants with C-Style Escapes #
178
179    PostgreSQL also accepts “escape” string constants, which are an
180    extension to the SQL standard. An escape string constant is specified
181    by writing the letter E (upper or lower case) just before the opening
182    single quote, e.g., E'foo'. (When continuing an escape string constant
183    across lines, write E only before the first opening quote.) Within an
184    escape string, a backslash character (\) begins a C-like backslash
185    escape sequence, in which the combination of backslash and following
186    character(s) represent a special byte value, as shown in Table 4.1.
187
188    Table 4.1. Backslash Escape Sequences
189    Backslash Escape Sequence Interpretation
190    \b backspace
191    \f form feed
192    \n newline
193    \r carriage return
194    \t tab
195    \o, \oo, \ooo (o = 0–7) octal byte value
196    \xh, \xhh (h = 0–9, A–F) hexadecimal byte value
197    \uxxxx, \Uxxxxxxxx (x = 0–9, A–F) 16 or 32-bit hexadecimal Unicode
198    character value
199
200    Any other character following a backslash is taken literally. Thus, to
201    include a backslash character, write two backslashes (\\). Also, a
202    single quote can be included in an escape string by writing \', in
203    addition to the normal way of ''.
204
205    It is your responsibility that the byte sequences you create,
206    especially when using the octal or hexadecimal escapes, compose valid
207    characters in the server character set encoding. A useful alternative
208    is to use Unicode escapes or the alternative Unicode escape syntax,
209    explained in Section 4.1.2.3; then the server will check that the
210    character conversion is possible.
211
212 Caution
213
214    If the configuration parameter standard_conforming_strings is off, then
215    PostgreSQL recognizes backslash escapes in both regular and escape
216    string constants. However, as of PostgreSQL 9.1, the default is on,
217    meaning that backslash escapes are recognized only in escape string
218    constants. This behavior is more standards-compliant, but might break
219    applications which rely on the historical behavior, where backslash
220    escapes were always recognized. As a workaround, you can set this
221    parameter to off, but it is better to migrate away from using backslash
222    escapes. If you need to use a backslash escape to represent a special
223    character, write the string constant with an E.
224
225    In addition to standard_conforming_strings, the configuration
226    parameters escape_string_warning and backslash_quote govern treatment
227    of backslashes in string constants.
228
229    The character with the code zero cannot be in a string constant.
230
231 4.1.2.3. String Constants with Unicode Escapes #
232
233    PostgreSQL also supports another type of escape syntax for strings that
234    allows specifying arbitrary Unicode characters by code point. A Unicode
235    escape string constant starts with U& (upper or lower case letter U
236    followed by ampersand) immediately before the opening quote, without
237    any spaces in between, for example U&'foo'. (Note that this creates an
238    ambiguity with the operator &. Use spaces around the operator to avoid
239    this problem.) Inside the quotes, Unicode characters can be specified
240    in escaped form by writing a backslash followed by the four-digit
241    hexadecimal code point number or alternatively a backslash followed by
242    a plus sign followed by a six-digit hexadecimal code point number. For
243    example, the string 'data' could be written as
244 U&'d\0061t\+000061'
245
246    The following less trivial example writes the Russian word “slon”
247    (elephant) in Cyrillic letters:
248 U&'\0441\043B\043E\043D'
249
250    If a different escape character than backslash is desired, it can be
251    specified using the UESCAPE clause after the string, for example:
252 U&'d!0061t!+000061' UESCAPE '!'
253
254    The escape character can be any single character other than a
255    hexadecimal digit, the plus sign, a single quote, a double quote, or a
256    whitespace character.
257
258    To include the escape character in the string literally, write it
259    twice.
260
261    Either the 4-digit or the 6-digit escape form can be used to specify
262    UTF-16 surrogate pairs to compose characters with code points larger
263    than U+FFFF, although the availability of the 6-digit form technically
264    makes this unnecessary. (Surrogate pairs are not stored directly, but
265    are combined into a single code point.)
266
267    If the server encoding is not UTF-8, the Unicode code point identified
268    by one of these escape sequences is converted to the actual server
269    encoding; an error is reported if that's not possible.
270
271    Also, the Unicode escape syntax for string constants only works when
272    the configuration parameter standard_conforming_strings is turned on.
273    This is because otherwise this syntax could confuse clients that parse
274    the SQL statements to the point that it could lead to SQL injections
275    and similar security issues. If the parameter is set to off, this
276    syntax will be rejected with an error message.
277
278 4.1.2.4. Dollar-Quoted String Constants #
279
280    While the standard syntax for specifying string constants is usually
281    convenient, it can be difficult to understand when the desired string
282    contains many single quotes, since each of those must be doubled. To
283    allow more readable queries in such situations, PostgreSQL provides
284    another way, called “dollar quoting”, to write string constants. A
285    dollar-quoted string constant consists of a dollar sign ($), an
286    optional “tag” of zero or more characters, another dollar sign, an
287    arbitrary sequence of characters that makes up the string content, a
288    dollar sign, the same tag that began this dollar quote, and a dollar
289    sign. For example, here are two different ways to specify the string
290    “Dianne's horse” using dollar quoting:
291 $$Dianne's horse$$
292 $SomeTag$Dianne's horse$SomeTag$
293
294    Notice that inside the dollar-quoted string, single quotes can be used
295    without needing to be escaped. Indeed, no characters inside a
296    dollar-quoted string are ever escaped: the string content is always
297    written literally. Backslashes are not special, and neither are dollar
298    signs, unless they are part of a sequence matching the opening tag.
299
300    It is possible to nest dollar-quoted string constants by choosing
301    different tags at each nesting level. This is most commonly used in
302    writing function definitions. For example:
303 $function$
304 BEGIN
305     RETURN ($1 ~ $q$[\t\r\n\v\\]$q$);
306 END;
307 $function$
308
309    Here, the sequence $q$[\t\r\n\v\\]$q$ represents a dollar-quoted
310    literal string [\t\r\n\v\\], which will be recognized when the function
311    body is executed by PostgreSQL. But since the sequence does not match
312    the outer dollar quoting delimiter $function$, it is just some more
313    characters within the constant so far as the outer string is concerned.
314
315    The tag, if any, of a dollar-quoted string follows the same rules as an
316    unquoted identifier, except that it cannot contain a dollar sign. Tags
317    are case sensitive, so $tag$String content$tag$ is correct, but
318    $TAG$String content$tag$ is not.
319
320    A dollar-quoted string that follows a keyword or identifier must be
321    separated from it by whitespace; otherwise the dollar quoting delimiter
322    would be taken as part of the preceding identifier.
323
324    Dollar quoting is not part of the SQL standard, but it is often a more
325    convenient way to write complicated string literals than the
326    standard-compliant single quote syntax. It is particularly useful when
327    representing string constants inside other constants, as is often
328    needed in procedural function definitions. With single-quote syntax,
329    each backslash in the above example would have to be written as four
330    backslashes, which would be reduced to two backslashes in parsing the
331    original string constant, and then to one when the inner string
332    constant is re-parsed during function execution.
333
334 4.1.2.5. Bit-String Constants #
335
336    Bit-string constants look like regular string constants with a B (upper
337    or lower case) immediately before the opening quote (no intervening
338    whitespace), e.g., B'1001'. The only characters allowed within
339    bit-string constants are 0 and 1.
340
341    Alternatively, bit-string constants can be specified in hexadecimal
342    notation, using a leading X (upper or lower case), e.g., X'1FF'. This
343    notation is equivalent to a bit-string constant with four binary digits
344    for each hexadecimal digit.
345
346    Both forms of bit-string constant can be continued across lines in the
347    same way as regular string constants. Dollar quoting cannot be used in
348    a bit-string constant.
349
350 4.1.2.6. Numeric Constants #
351
352    Numeric constants are accepted in these general forms:
353 digits
354 digits.[digits][e[+-]digits]
355 [digits].digits[e[+-]digits]
356 digitse[+-]digits
357
358    where digits is one or more decimal digits (0 through 9). At least one
359    digit must be before or after the decimal point, if one is used. At
360    least one digit must follow the exponent marker (e), if one is present.
361    There cannot be any spaces or other characters embedded in the
362    constant, except for underscores, which can be used for visual grouping
363    as described below. Note that any leading plus or minus sign is not
364    actually considered part of the constant; it is an operator applied to
365    the constant.
366
367    These are some examples of valid numeric constants:
368
369    42
370    3.5
371    4.
372    .001
373    5e2
374    1.925e-3
375
376    Additionally, non-decimal integer constants are accepted in these
377    forms:
378 0xhexdigits
379 0ooctdigits
380 0bbindigits
381
382    where hexdigits is one or more hexadecimal digits (0-9, A-F), octdigits
383    is one or more octal digits (0-7), and bindigits is one or more binary
384    digits (0 or 1). Hexadecimal digits and the radix prefixes can be in
385    upper or lower case. Note that only integers can have non-decimal
386    forms, not numbers with fractional parts.
387
388    These are some examples of valid non-decimal integer constants:
389
390    0b100101
391    0B10011001
392    0o273
393    0O755
394    0x42f
395    0XFFFF
396
397    For visual grouping, underscores can be inserted between digits. These
398    have no further effect on the value of the constant. For example:
399
400    1_500_000_000
401    0b10001000_00000000
402    0o_1_755
403    0xFFFF_FFFF
404    1.618_034
405
406    Underscores are not allowed at the start or end of a numeric constant
407    or a group of digits (that is, immediately before or after the decimal
408    point or the exponent marker), and more than one underscore in a row is
409    not allowed.
410
411    A numeric constant that contains neither a decimal point nor an
412    exponent is initially presumed to be type integer if its value fits in
413    type integer (32 bits); otherwise it is presumed to be type bigint if
414    its value fits in type bigint (64 bits); otherwise it is taken to be
415    type numeric. Constants that contain decimal points and/or exponents
416    are always initially presumed to be type numeric.
417
418    The initially assigned data type of a numeric constant is just a
419    starting point for the type resolution algorithms. In most cases the
420    constant will be automatically coerced to the most appropriate type
421    depending on context. When necessary, you can force a numeric value to
422    be interpreted as a specific data type by casting it. For example, you
423    can force a numeric value to be treated as type real (float4) by
424    writing:
425 REAL '1.23'  -- string style
426 1.23::REAL   -- PostgreSQL (historical) style
427
428    These are actually just special cases of the general casting notations
429    discussed next.
430
431 4.1.2.7. Constants of Other Types #
432
433    A constant of an arbitrary type can be entered using any one of the
434    following notations:
435 type 'string'
436 'string'::type
437 CAST ( 'string' AS type )
438
439    The string constant's text is passed to the input conversion routine
440    for the type called type. The result is a constant of the indicated
441    type. The explicit type cast can be omitted if there is no ambiguity as
442    to the type the constant must be (for example, when it is assigned
443    directly to a table column), in which case it is automatically coerced.
444
445    The string constant can be written using either regular SQL notation or
446    dollar-quoting.
447
448    It is also possible to specify a type coercion using a function-like
449    syntax:
450 typename ( 'string' )
451
452    but not all type names can be used in this way; see Section 4.2.9 for
453    details.
454
455    The ::, CAST(), and function-call syntaxes can also be used to specify
456    run-time type conversions of arbitrary expressions, as discussed in
457    Section 4.2.9. To avoid syntactic ambiguity, the type 'string' syntax
458    can only be used to specify the type of a simple literal constant.
459    Another restriction on the type 'string' syntax is that it does not
460    work for array types; use :: or CAST() to specify the type of an array
461    constant.
462
463    The CAST() syntax conforms to SQL. The type 'string' syntax is a
464    generalization of the standard: SQL specifies this syntax only for a
465    few data types, but PostgreSQL allows it for all types. The syntax with
466    :: is historical PostgreSQL usage, as is the function-call syntax.
467
468 4.1.3. Operators #
469
470    An operator name is a sequence of up to NAMEDATALEN-1 (63 by default)
471    characters from the following list:
472
473    + - * / < > = ~ ! @ # % ^ & | ` ?
474
475    There are a few restrictions on operator names, however:
476      * -- and /* cannot appear anywhere in an operator name, since they
477        will be taken as the start of a comment.
478      * A multiple-character operator name cannot end in + or -, unless the
479        name also contains at least one of these characters:
480        ~ ! @ # % ^ & | ` ?
481        For example, @- is an allowed operator name, but *- is not. This
482        restriction allows PostgreSQL to parse SQL-compliant queries
483        without requiring spaces between tokens.
484
485    When working with non-SQL-standard operator names, you will usually
486    need to separate adjacent operators with spaces to avoid ambiguity. For
487    example, if you have defined a prefix operator named @, you cannot
488    write X*@Y; you must write X* @Y to ensure that PostgreSQL reads it as
489    two operator names not one.
490
491 4.1.4. Special Characters #
492
493    Some characters that are not alphanumeric have a special meaning that
494    is different from being an operator. Details on the usage can be found
495    at the location where the respective syntax element is described. This
496    section only exists to advise the existence and summarize the purposes
497    of these characters.
498      * A dollar sign ($) followed by digits is used to represent a
499        positional parameter in the body of a function definition or a
500        prepared statement. In other contexts the dollar sign can be part
501        of an identifier or a dollar-quoted string constant.
502      * Parentheses (()) have their usual meaning to group expressions and
503        enforce precedence. In some cases parentheses are required as part
504        of the fixed syntax of a particular SQL command.
505      * Brackets ([]) are used to select the elements of an array. See
506        Section 8.15 for more information on arrays.
507      * Commas (,) are used in some syntactical constructs to separate the
508        elements of a list.
509      * The semicolon (;) terminates an SQL command. It cannot appear
510        anywhere within a command, except within a string constant or
511        quoted identifier.
512      * The colon (:) is used to select “slices” from arrays. (See
513        Section 8.15.) In certain SQL dialects (such as Embedded SQL), the
514        colon is used to prefix variable names.
515      * The asterisk (*) is used in some contexts to denote all the fields
516        of a table row or composite value. It also has a special meaning
517        when used as the argument of an aggregate function, namely that the
518        aggregate does not require any explicit parameter.
519      * The period (.) is used in numeric constants, and to separate
520        schema, table, and column names.
521
522 4.1.5. Comments #
523
524    A comment is a sequence of characters beginning with double dashes and
525    extending to the end of the line, e.g.:
526 -- This is a standard SQL comment
527
528    Alternatively, C-style block comments can be used:
529 /* multiline comment
530  * with nesting: /* nested block comment */
531  */
532
533    where the comment begins with /* and extends to the matching occurrence
534    of */. These block comments nest, as specified in the SQL standard but
535    unlike C, so that one can comment out larger blocks of code that might
536    contain existing block comments.
537
538    A comment is removed from the input stream before further syntax
539    analysis and is effectively replaced by whitespace.
540
541 4.1.6. Operator Precedence #
542
543    Table 4.2 shows the precedence and associativity of the operators in
544    PostgreSQL. Most operators have the same precedence and are
545    left-associative. The precedence and associativity of the operators is
546    hard-wired into the parser. Add parentheses if you want an expression
547    with multiple operators to be parsed in some other way than what the
548    precedence rules imply.
549
550    Table 4.2. Operator Precedence (highest to lowest)
551    Operator/Element Associativity Description
552    . left table/column name separator
553    :: left PostgreSQL-style typecast
554    [ ] left array element selection
555    + - right unary plus, unary minus
556    COLLATE left collation selection
557    AT left AT TIME ZONE, AT LOCAL
558    ^ left exponentiation
559    * / % left multiplication, division, modulo
560    + - left addition, subtraction
561    (any other operator) left all other native and user-defined operators
562    BETWEEN IN LIKE ILIKE SIMILAR   range containment, set membership,
563    string matching
564    < > = <= >= <>   comparison operators
565    IS ISNULL NOTNULL   IS TRUE, IS FALSE, IS NULL, IS DISTINCT FROM, etc.
566    NOT right logical negation
567    AND left logical conjunction
568    OR left logical disjunction
569
570    Note that the operator precedence rules also apply to user-defined
571    operators that have the same names as the built-in operators mentioned
572    above. For example, if you define a “+” operator for some custom data
573    type it will have the same precedence as the built-in “+” operator, no
574    matter what yours does.
575
576    When a schema-qualified operator name is used in the OPERATOR syntax,
577    as for example in:
578 SELECT 3 OPERATOR(pg_catalog.+) 4;
579
580    the OPERATOR construct is taken to have the default precedence shown in
581    Table 4.2 for “any other operator”. This is true no matter which
582    specific operator appears inside OPERATOR().
583
584 Note
585
586    PostgreSQL versions before 9.5 used slightly different operator
587    precedence rules. In particular, <= >= and <> used to be treated as
588    generic operators; IS tests used to have higher priority; and NOT
589    BETWEEN and related constructs acted inconsistently, being taken in
590    some cases as having the precedence of NOT rather than BETWEEN. These
591    rules were changed for better compliance with the SQL standard and to
592    reduce confusion from inconsistent treatment of logically equivalent
593    constructs. In most cases, these changes will result in no behavioral
594    change, or perhaps in “no such operator” failures which can be resolved
595    by adding parentheses. However there are corner cases in which a query
596    might change behavior without any parsing error being reported.