Value expressions are used in a variety of contexts, such
as in the target list of the SELECT command, as
new column values in INSERT or
UPDATE, or in search conditions in a number of
commands. The result of a value expression is sometimes called a
scalar, to distinguish it from the result of
a table expression (which is a table). Value expressions are
therefore also called scalar expressions (or
even simply expressions). The expression
syntax allows the calculation of values from primitive parts using
arithmetic, logical, set, and other operations.
A value expression is one of the following:
A constant or literal value; see Section 1.1.2.
A column reference.
A positional parameter reference, in the body of a function declaration.
An operator invocation.
A function call.
An aggregate expression.
A type cast.
A scalar subquery.
Another value expression in parentheses, useful to group subexpressions and override precedence.
In addition to this list, there are a number of constructs 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 Chapter 6. An example is the IS NULL
clause.
We have already discussed constants in Section 1.1.2. The following sections discuss
the remaining options.
A column can be referenced in the form
correlation.columnname
or
correlation.columnname[subscript]
(Here, the brackets [ ] are meant to appear literally.)
correlation is the name of a
table (possibly qualified), or an alias for a table defined by means of a
FROM clause, or
the key words NEW or OLD.
(NEW and OLD can only appear in rewrite rules,
while other correlation names can be used in any SQL statement.)
The correlation name and separating dot may be omitted if the column name
is unique across all the tables being used in the current query. (See also Chapter 4.)
If column is of an array type, then the
optional subscript selects a specific
element or elements in the array. If no subscript is provided, then the
whole array is selected. (See Section 5.12 for more about
arrays.)
A positional parameter reference is used to indicate a parameter
that is supplied externally to an SQL statement. Parameters are
used in SQL function definitions and in prepared queries.
The form of a parameter reference is:
$number
For example, consider the definition of a function,
dept, as
CREATE FUNCTION dept(text) RETURNS dept
AS 'SELECT * FROM dept WHERE name = $1'
LANGUAGE SQL;
Here the $1 will be replaced by the first
function argument when the function is invoked.
There are three possible syntaxes for an operator invocation:
expression operator expression (binary infix operator) |
operator expression (unary prefix operator) |
expression operator (unary postfix operator) |
where the
operator token follows the syntax
rules of
Section 1.1.3, or is one of the
keywords
AND,
OR, and
NOT, or is a qualified operator name
OPERATOR(schema.operatorname)
Which particular operators exist and whether
they are unary or binary depends on what operators have been
defined by the system or the user. Chapter 6
describes the built-in operators.
The syntax for a function call is the name of a function
(possibly qualified with a schema name), followed by its argument list
enclosed in parentheses:
function ([expression [, expression ... ]] )
For example, the following computes the square root of 2:
sqrt(2)
The list of built-in functions is in Chapter 6.
Other functions may be added by the user.
An aggregate expression 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:
aggregate_name (expression)
aggregate_name (ALL expression)
aggregate_name (DISTINCT expression)
aggregate_name ( * )
where aggregate_name is a previously
defined aggregate (possibly a qualified name), and
expression is
any value expression that does not itself contain an aggregate
expression.
The first form of aggregate expression invokes the aggregate
across all input rows for which the given expression yields a
non-null value. (Actually, it is up to the aggregate function
whether to ignore null values or not --- but all the standard ones do.)
The second form is the same as the first, since
ALL 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 count() aggregate function.
For example, count(*) yields the total number
of input rows; count(f1) yields the number of
input rows in which f1 is non-null;
count(distinct f1) yields the number of
distinct non-null values of f1.
The predefined aggregate functions are described in Section 6.14. Other aggregate functions may be added
by the user.
A type cast specifies a conversion from one data type to another.
PostgreSQL accepts two equivalent syntaxes
for type casts:
CAST ( expression AS type )
expression::type
The CAST syntax conforms to SQL; the syntax with
:: is historical PostgreSQL
usage.
When a cast is applied to a value expression of a known type, it
represents a run-time type conversion. The cast will succeed only
if a suitable type conversion function is available. Notice that this
is subtly different from the use of casts with constants, as shown in
Section 1.1.2.4. A cast applied to an
unadorned string literal represents the initial assignment of a type
to a literal constant value, and so it will succeed for any type
(if the contents of the string literal are acceptable input syntax for the
data type).
An explicit type cast may usually be omitted if there is no ambiguity as
to the type that a value expression must produce (for example, when it is
assigned to a table column); the system will automatically apply a
type cast in such cases. However, automatic casting is only done for
casts that are marked "OK to apply implicitly"
in the system catalogs. Other casts must be invoked with
explicit casting syntax. This restriction is intended to prevent
surprising conversions from being applied silently.
It is also possible to specify a type cast using a function-like
syntax:
typename ( expression )
However, this only works for types whose names are also valid as
function names. For example, double precision
can't be used this way, but the equivalent float8
can. Also, the names interval, time, and
timestamp can only be used in this fashion if they are
double-quoted, because of syntactic conflicts. Therefore, the use of
the function-like cast syntax leads to inconsistencies and should
probably be avoided in new applications.
(The function-like syntax is in fact just a function call. When
one of the two standard cast syntaxes is used to do a run-time
conversion, it will internally invoke a registered function to
perform the conversion. By convention, these conversion functions
have the same name as their output type, but this is not something
that a portable application should rely on.)
A scalar subquery is an ordinary
SELECT query in parentheses that returns exactly one
row with one column. (See Chapter 4 for information about writing queries.)
The SELECT query is executed
and the single returned value is used in the surrounding value expression.
It is an error to use a query that
returns more than one row or more than one column as a scalar subquery.
(But if, during a particular execution, the subquery returns no rows,
there is no error; the scalar result is taken to be null.)
The subquery can refer to variables from the surrounding query,
which will act as constants during any one evaluation of the subquery.
See also Section 6.15.
For example, the following finds the largest city population in each
state:
SELECT name, (SELECT max(pop) FROM cities WHERE cities.state = states.name)
FROM states;
The order of evaluation of subexpressions is not defined. In
particular, the inputs of an operator or function are not necessarily
evaluated left-to-right or in any other fixed order.
Furthermore, if the result of an expression can be determined by
evaluating only some parts of it, then other subexpressions
might not be evaluated at all. For instance, if one wrote
SELECT true OR somefunc();
then somefunc() would (probably) not be called
at all. The same would be the case if one wrote
SELECT somefunc() OR true;
Note that this is not the same as the left-to-right
"short-circuiting" of Boolean operators that is found
in some programming languages.
As a consequence, it is unwise to use functions with side effects
as part of complex expressions. It is particularly dangerous to
rely on side effects or evaluation order in WHERE and HAVING clauses,
since those clauses are extensively reprocessed as part of
developing an execution plan. Boolean
expressions (AND/OR/NOT combinations) in those clauses may be reorganized
in any manner allowed by the laws of Boolean algebra.
When it is essential to force evaluation order, a CASE
construct (see Section 6.12) may be
used. For example, this is an untrustworthy way of trying to
avoid division by zero in a WHERE clause:
SELECT ... WHERE x <> 0 AND y/x > 1.5;
But this is safe:
SELECT ... WHERE CASE WHEN x <> 0 THEN y/x > 1.5 ELSE false END;
A CASE construct used in this fashion will defeat optimization attempts,
so it should only be done when necessary.