Conditional expressions¶
CASE
¶
The standard SQL CASE
expression has two forms. The "simple" form searches each value
expression from left to right until it finds one that equals expression
:
The result
is the value
corresponding to the matched condition. In case no match is identified, the result
from the ELSE clause, if present, is returned; otherwise, null is the result. For example:
The "searched" form assesses each boolean condition
from left to right until one becomes true
and then returns the corresponding result
:
If no conditions are true, the result
from the ELSE
clause is
returned if it exists, otherwise null is returned.For Example:
SQL routines can use CASE
statementsthat use a slightly
different syntax from the CASE expressions. Specifically note the requirements
for terminating each clause with a semicolon ;
and the usage of END CASE
.
IF()
¶
The IF expression comes in two forms: one provides only a true_value, while the other offers both a true_value and a false_value.
Function | Description |
---|---|
if(condition, true_value) |
Evaluates and returns true_value if condition is true, otherwise null is returned and true_value is not evaluated. |
if(condition, true_value, false_value) |
Evaluates and returns true_value if condition is true, otherwise evaluates and returns false_value . |
COALESCE
¶
Function | Description |
---|---|
coalesce(value1, value2[, ...]) |
Returns the first non-null value in the argument list. Like a CASE expression, arguments are only evaluated if necessary. |
NULLIF
¶
Function | Description |
---|---|
nullif(value1, value2) |
Returns null if value1 equals value2 , otherwise returns value1 . |
TRY()
¶
In cases where it is preferable for queries to produce NULL
or default values instead of failing when corrupt or invalid data is encountered, the TRY
function may be useful. To specify default values, the TRY
function can be used in conjunction with the COALESCE
function.
The following errors are handled by TRY
:
- Division by zero
- Invalid cast or function argument
- Numeric value out of range
Function | Description |
---|---|
try(expression) |
Evaluates an expression and handles certain types of errors by returning NULL . |
Examples¶
Source table with some invalid data:
origin_state | origin_zip | packages | total_cost
--------------+------------+----------+------------
California | 94131 | 25 | 100
California | P332a | 5 | 72
California | 94025 | 0 | 155
New Jersey | 08544 | 225 | 490
(4 rows)
Query failure without TRY
:
NULL
values with TRY
:
Query failure without TRY
:
Default values with TRY
and COALESCE
: