Structured Query Language (SQL) is a language used for creating, maintaining, and querying relational databases. This chapter describes the general syntax of SQL.
SQL input consists of a sequence of commands. A command is composed of a sequence of tokens, terminated by a semicolon (";"). The end of the input stream also terminates a command. Which tokens are valid depends on the syntax of the particular command.
A token can be a key word, an identifier, a quoted identifier, a literal (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 the case only if a special character is adjacent to some other token type).
Additionally, SQL input may include comments. These are not tokens; they are effectively equivalent to whitespace.
For example, the following is (syntactically) valid SQL input:
SELECT * FROM MY_TABLE; UPDATE MY_TABLE SET A = 5; INSERT INTO MY_TABLE VALUES (3, 'hi there'); |
The SQL syntax is not very consistent regarding which 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 "SELECT", an "UPDATE", and an "INSERT" command. However, the syntax rules for SQL statements can vary. For instance, the UPDATE command always requires a SET token to appear in a certain position, and the particular variation of the INSERT shown above also requires a VALUES token in order to be complete. The precise syntax rules for each command are described in the Reference section of this manual.
Tokens such as SELECT, UPDATE, or VALUES in the example above are examples of key words, that is, words that have a fixed meaning in the SQL language. The tokens MY_TABLE and A are examples of identifiers. They identify names of tables, columns, or other database objects, depending on the command in which they are used. Identifiers are sometimes simply called "names". Key words and identifiers have the same lexical structure, which means that it can be difficult to determine if a token is an identifier or a key word without knowing SQL. A complete list of key words can be found in Appendix A.
SQL identifiers and key words must begin with a letter (a-z, but also letters with diacritical marks and non-Latin letters) or an underscore (_). Subsequent characters in an identifier or key word can be letters, digits (0-9), or underscores, although the SQL standard will not define a key word that contains digits or starts or ends with an underscore.
In PostgreSQL, the system uses no more than NAMEDATALEN-1 characters of an identifier; longer names can be written in commands, but they will be truncated. By default, NAMEDATALEN is 32, so the maximum identifier length in PostgreSQL is 31. It is necessary to rebuild the PostgreSQL binaries to increase this limit
Identifier and key word names are case insensitive. Therefore
UPDATE MY_TABLE SET A = 5; |
uPDaTE my_TabLE SeT a = 5; |
UPDATE my_table SET a = 5; |
There is a second kind of identifier: the delimited identifier or quoted identifier. This identifier is formed by enclosing an arbitrary sequence of characters in double-quotes ("). A delimited identifier is always an identifier, never a key word. So "select" could be used to refer to a column or table named "select", whereas an unquoted select would be taken as a key word 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 this:
UPDATE "my_table" SET "a" = 5; |
Quoted identifiers can contain any character other than a double quote itself. This allows you to construct table or column names that would otherwise not be possible, such as ones containing spaces or ampersands. The length limitation still applies.
Quoting an identifier also makes it case-sensitive, whereas unquoted names are always converted to lower case. For example, the identifiers FOO, foo and "foo" are considered the same by PostgreSQL, but "Foo" and "FOO" are different from these three and each other.
PostgreSQL's converting of unquoted names to lower case is incompatible with the SQL standard, which says that unquoted names should be folded to upper case. Thus, foo should be equivalent to "FOO" not "foo" according to the standard. If you want to write portable applications you are advised to always quote a particular name or never quote it. |
There are four kinds of implicitly typed constants in PostgreSQL:
strings
bit strings
integers
floating point numbers.
The implicit constants are described below; explicit constants are discussed afterwards.
A string constant in SQL is an arbitrary sequence of characters bounded by single quotes, for example, 'This is a string'. SQL allows single quotes to be embedded in strings by typing two adjacent single quotes (for example, 'Dianne''s horse'). In PostgreSQL single quotes can alternatively be escaped with a backslash ("\", for example, 'Dianne\'s horse').
Backslash escapes, as used in C, are also available:
is a backspace
is a form feed
is a new line
is a carriage return
is a tab
where xxx is an octal number.
Any other character following a backslash is taken literally. Thus, to include a backslash in a string constant, type two backslashes.
The character with the code zero cannot be in a string constant.
Two string constants that are separated only by whitespace with at least one newline are concatenated and effectively treated as if the string had been written in one constant. For example:
SELECT 'foo' 'bar'; |
SELECT 'foobar'; |
SELECT 'foo' 'bar'; |
Bit string constants look like string constants with a B (upper or lower case) immediately before the opening quote (no intervening whitespace), for example, B'1001'. The only characters allowed within bit string constants are 0 and 1. Bit string constants can be continued across lines in the same way as regular string constants.
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 integer 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.)
Floating point constants are accepted in these general forms:
digits.[digits][e[+-]digits] [digits].digits[e[+-]digits] digitse[+-]digits |
Floating point constants are of type DOUBLE PRECISION. REAL can be specified explicitly by using SQL string notation or PostgreSQL type notation:
REAL '1.23' -- string style '1.23'::REAL -- PostgreSQL (historical) style |
A constant of an arbitrary type can be entered using any one of the following notations:
type 'string' 'string'::type CAST ('string' AS type) |
It is also possible to specify a type coercion using a function-like syntax:
typename (value) |
The ::, CAST(), and function-call syntaxes can also be used to specify runtime type conversions of arbitrary expressions, as discussed in the Section called Type Casts. But the form type 'string' can be used only to specify the type of a literal constant. Another restriction on type 'string' is that it does not work for array types; use :: or CAST() to specify the type of an array constant.
The general format of an array constant is:
'{ val1 delim val2 delim ... }' |
'{{1,2,3},{4,5,6},{7,8,9}}' |
Individual array elements can be placed between double-quote marks (") to avoid ambiguity problems with respect to white space. Without quote marks, the array-value parser will skip leading white space.
(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.)
An operator is a sequence of up to NAMEDATALEN-1 (31 by default) characters from the following list:
+ - * / < > = ~ ! @ # % ^ & | ` ? $
There are a few restrictions on operator names, however:"$" (dollar) cannot be a single-character operator, although it can be part of a multi-character operator name.
-- and /* cannot appear anywhere in an operator name, since they will be taken as the start of a comment.
A multi-character operator name cannot end in "+" or "-", unless the name also contains at least one of these characters:
~ ! @ # % ^ & | ` ? $
For example, @- is an allowed operator name, but *- is not. This restriction allows PostgreSQL to parse SQL-compliant queries without requiring spaces between tokens.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 X*@Y; you must write X* @Y to ensure that PostgreSQL reads it as two operator names not one.
Some characters that are not alphanumeric have a special meaning that is different from being an operator. This section provides a summary of these characters. For details, refer to the location where their respective syntax element is described.
A dollar sign ($) 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.
Parentheses (()) 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.
Brackets ([]) are used to select the elements of an array. See the Section called Arrays in Chapter 2 for more information on arrays.
Commas (,) are used in some syntactical constructs to separate the elements of a list.
The semicolon (;) terminates an SQL command. It cannot appear anywhere within a command, except within a string constant or quoted identifier.
The colon (:) is used to select "slices" from arrays. (See the Section called Arrays in Chapter 2.) In certain SQL dialects (such as Embedded SQL), the colon is used to prefix variable names.
The asterisk (*) has a special meaning when used in the SELECT command or with the COUNT aggregate function.
The period (.) is used in floating point constants, and to separate table and column names.
A comment is an arbitrary sequence of characters beginning with double dashes and extending to the end of the line, for example:
-- This is a standard SQL92 comment |
Alternatively, C-style block comments can be used:
/* multi-line comment * with nesting: /* nested block comment */ */ |
A comment is removed from the input stream before further syntax analysis and is effectively replaced by whitespace.