PostgreSQL 8.2.23 Documentation
Prev | Fast Backward | Chapter 4. SQL Syntax | Fast Forward | Next

# 4.2. Value Expressions

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.

- A column reference.

- A positional parameter reference, in the body of a function definition or prepared statement.

- A subscripted expression.

- A field selection expression.

- An operator invocation.

- A function call.

- An aggregate expression.

- A type cast.

- A scalar subquery.

- An array constructor.

- A row constructor.

- 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 9. An example is the `IS NULL` clause.

We have already discussed constants in Section 4.1.2. The following sections discuss the remaining options.

## 4.2.1. Column References

A column can be referenced in the form

    correlation.columnname

`correlation` is the name of a table (possibly qualified with a schema name), or an alias for a table defined by means of a `FROM` clause, or one of 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 7.)

## 4.2.2. Positional Parameters

A positional parameter reference is used to indicate a value that is supplied externally to an SQL statement. Parameters are used in SQL function definitions and in prepared queries. Some client libraries also support specifying data values separately from the SQL command string, in which case parameters are used to refer to the out-of-line data values. 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` references the value of the first function argument whenever the function is invoked.

## 4.2.3. Subscripts

If an expression yields a value of an array type, then a specific element of the array value can be extracted by writing

    expression[subscript]

or multiple adjacent elements (an "array slice") can be extracted by writing

    expression[lower_subscript:upper_subscript]

(Here, the brackets `[ ]` are meant to appear literally.) Each `subscript` is itself an expression, which must yield an integer value.

In general the array `expression` must be parenthesized, but the parentheses may be omitted when the expression to be subscripted is just a column reference or positional parameter. Also, multiple subscripts can be concatenated when the original array is multidimensional. For example,

    mytable.arraycolumn[4]
    mytable.two_d_column[17][34]
    $1[10:42]
    (arrayfunction(a,b))[42]

The parentheses in the last example are required. See Section 8.10 for more about arrays.

## 4.2.4. Field Selection

If an expression yields a value of a composite type (row type), then a specific field of the row can be extracted by writing

    expression.fieldname

In general the row `expression` must be parenthesized, but the parentheses may be omitted when the expression to be selected from is just a table reference or positional parameter. For example,

    mytable.mycolumn
    $1.somecolumn
    (rowfunction(a,b)).col3

(Thus, a qualified column reference is actually just a special case of the field selection syntax.)

## 4.2.5. Operator Invocations

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 4.1.3, or is one of the key words `AND`, `OR`, and `NOT`, or is a qualified operator name in the form

    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 9 describes the built-in operators.

## 4.2.6. Function Calls

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 9. Other functions may be added by the user.

## 4.2.7. Aggregate Expressions

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 qualified with a schema 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(s) yield non-null values. (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 expressions 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 9.15. Other aggregate functions may be added by the user.

An aggregate expression may only appear in the result list or `HAVING` clause of a `SELECT` command. It is forbidden in other clauses, such as `WHERE`, because those clauses are logically evaluated before the results of aggregates are formed.

When an aggregate expression appears in a subquery (see Section 4.2.9 and Section 9.16), the aggregate is normally evaluated over the rows of the subquery. But an exception occurs if the aggregate's arguments contain only outer-level variables: the aggregate then belongs to the nearest such outer level, and is evaluated over the rows of that query. The aggregate expression as a whole is then an outer reference for the subquery it appears in, and acts as a constant over any one evaluation of that subquery. The restriction about appearing only in the result list or `HAVING` clause applies with respect to the query level that the aggregate belongs to.

> Note: PostgreSQL currently does not support `DISTINCT` with more than one input expression.

## 4.2.8. Type Casts

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 operation has been defined. Notice that this is subtly different from the use of casts with constants, as shown in Section 4.1.2.5. 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, and thus the "function-like syntax" is nothing more than a direct invocation of the underlying conversion function. Obviously, this is not something that a portable application should rely on.)

## 4.2.9. Scalar Subqueries

A scalar subquery is an ordinary `SELECT` query in parentheses that returns exactly one row with one column. (See Chapter 7 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 9.16 for other expressions involving subqueries.

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;

## 4.2.10. Array Constructors

An array constructor is an expression that builds an array value from values for its member elements. A simple array constructor consists of the key word `ARRAY`, a left square bracket `[`, one or more expressions (separated by commas) for the array element values, and finally a right square bracket `]`. For example,

    SELECT ARRAY[1,2,3+4];
      array
    ---------
     {1,2,7}
    (1 row)

The array element type is the common type of the member expressions, determined using the same rules as for `UNION` or `CASE` constructs (see Section 10.5).

Multidimensional array values can be built by nesting array constructors. In the inner constructors, the key word `ARRAY` may be omitted. For example, these produce the same result:

    SELECT ARRAY[ARRAY[1,2], ARRAY[3,4]];
         array
    ---------------
     {{1,2},{3,4}}
    (1 row)

    SELECT ARRAY[[1,2],[3,4]];
         array
    ---------------
     {{1,2},{3,4}}
    (1 row)

Since multidimensional arrays must be rectangular, inner constructors at the same level must produce sub-arrays of identical dimensions.

Multidimensional array constructor elements can be anything yielding an array of the proper kind, not only a sub-`ARRAY` construct. For example:

    CREATE TABLE arr(f1 int[], f2 int[]);

    INSERT INTO arr VALUES (ARRAY[[1,2],[3,4]], ARRAY[[5,6],[7,8]]);

    SELECT ARRAY[f1, f2, '{{9,10},{11,12}}'::int[]] FROM arr;
                         array
    ------------------------------------------------
     {{{1,2},{3,4}},{{5,6},{7,8}},{{9,10},{11,12}}}
    (1 row)

It is also possible to construct an array from the results of a subquery. In this form, the array constructor is written with the key word `ARRAY` followed by a parenthesized (not bracketed) subquery. For example:

    SELECT ARRAY(SELECT oid FROM pg_proc WHERE proname LIKE 'bytea%');
                              ?column?
    -------------------------------------------------------------
     {2011,1954,1948,1952,1951,1244,1950,2005,1949,1953,2006,31}
    (1 row)

The subquery must return a single column. The resulting one-dimensional array will have an element for each row in the subquery result, with an element type matching that of the subquery's output column.

The subscripts of an array value built with `ARRAY` always begin with one. For more information about arrays, see Section 8.10.

## 4.2.11. Row Constructors

A row constructor is an expression that builds a row value (also called a composite value) from values for its member fields. A row constructor consists of the key word `ROW`, a left parenthesis, zero or more expressions (separated by commas) for the row field values, and finally a right parenthesis. For example,

    SELECT ROW(1,2.5,'this is a test');

The key word `ROW` is optional when there is more than one expression in the list.

A row constructor can include the syntax `rowvalue``.*`, which will be expanded to a list of the elements of the row value, just as occurs when the `.*` syntax is used at the top level of a `SELECT` list. For example, if table `t` has columns `f1` and `f2`, these are the same:

    SELECT ROW(t.*, 42) FROM t;
    SELECT ROW(t.f1, t.f2, 42) FROM t;

> Note: Before PostgreSQL 8.2, the `.*` syntax was not expanded, so that writing `ROW(t.*, 42)` created a two-field row whose first field was another row value. The new behavior is usually more useful. If you need the old behavior of nested row values, write the inner row value without `.*`, for instance `ROW(t, 42)`.

By default, the value created by a `ROW` expression is of an anonymous record type. If necessary, it can be cast to a named composite type — either the row type of a table, or a composite type created with `CREATE TYPE AS`. An explicit cast may be needed to avoid ambiguity. For example:

    CREATE TABLE mytable(f1 int, f2 float, f3 text);

    CREATE FUNCTION getf1(mytable) RETURNS int AS 'SELECT $1.f1' LANGUAGE SQL;

    -- No cast needed since only one getf1() exists
    SELECT getf1(ROW(1,2.5,'this is a test'));
     getf1
    -------
         1
    (1 row)

    CREATE TYPE myrowtype AS (f1 int, f2 text, f3 numeric);

    CREATE FUNCTION getf1(myrowtype) RETURNS int AS 'SELECT $1.f1' LANGUAGE SQL;

    -- Now we need a cast to indicate which function to call:
    SELECT getf1(ROW(1,2.5,'this is a test'));
    ERROR:  function getf1(record) is not unique

    SELECT getf1(ROW(1,2.5,'this is a test')::mytable);
     getf1
    -------
         1
    (1 row)

    SELECT getf1(CAST(ROW(11,'this is a test',2.5) AS myrowtype));
     getf1
    -------
        11
    (1 row)

Row constructors can be used to build composite values to be stored in a composite-type table column, or to be passed to a function that accepts a composite parameter. Also, it is possible to compare two row values or test a row with `IS NULL` or `IS NOT NULL`, for example

    SELECT ROW(1,2.5,'this is a test') = ROW(1, 3, 'not the same');

    SELECT ROW(table.*) IS NULL FROM table;  -- detect all-null rows

For more detail see Section 9.17. Row constructors can also be used in connection with subqueries, as discussed in Section 9.16.

## 4.2.12. Expression Evaluation Rules

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 9.13) 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. (In this particular example, it would doubtless be best to sidestep the problem by writing `y > 1.5*x` instead.)

Prev | Home | Next
Lexical Structure | Up | Data Definition