PostgreSQL 8.0.1 Documentation | ||||
---|---|---|---|---|
Prev | Fast Backward | Chapter 9. Functions and Operators | Fast Forward | Next |
9.13. Conditional Expressions
This section describes the SQL-compliant conditional expressions available in PostgreSQL.
Tip: If your needs go beyond the capabilities of these conditional expressions you might want to consider writing a stored procedure in a more expressive programming language.
9.13.1. CASE
The SQL CASE expression is a generic conditional expression, similar to if/else statements in other languages:
CASE clauses can be used wherever an expression is valid. condition is an expression that returns a boolean result. If the result is true then the value of the CASE expression is the result that follows the condition. If the result is false any subsequent WHEN clauses are searched in the same manner. If no WHEN condition is true then the value of the case expression is the result in the ELSE clause. If the ELSE clause is omitted and no condition matches, the result is null.
An example:
The data types of all the result expressions must be convertible to a single output type. See Section 10.5 for more detail.
The following "simple" CASE expression is a specialized variant of the general form above:
The expression is computed and compared to all the value specifications in the WHEN clauses until one is found that is equal. If no match is found, the result in the ELSE clause (or a null value) is returned. This is similar to the switch
statement in C.
The example above can be written using the simple CASE syntax:
A CASE expression does not evaluate any subexpressions that are not needed to determine the result. For example, this is a possible way of avoiding a division-by-zero failure:
9.13.2. COALESCE
The COALESCE
function returns the first of its arguments that is not null. Null is returned only if all arguments are null. This is often useful to substitute a default value for null values when data is retrieved for display, for example:
Like a CASE expression, COALESCE
will not evaluate arguments that are not needed to determine the result; that is, arguments to the right of the first non-null argument are not evaluated.
9.13.3. NULLIF
The NULLIF
function returns a null value if and only if value1 and value2 are equal. Otherwise it returns value1. This can be used to perform the inverse operation of the COALESCE
example given above: