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
for the matching value
is returned.
If no match is found, the result
from the ELSE
clause is
returned if it exists, otherwise null is returned. Example:
The “searched” form evaluates each boolean condition
from left
to right until one is true and returns the matching result
:
If no conditions are true, the result
from the ELSE
clause is
returned if it exists, otherwise null is returned. Example:
SQL routines can use CASE
statements that 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 has two forms, one supplying only a
true_value
and the other supplying both a true_value
and a
false_value
:
Evaluates and returns true_value
if condition
is true,
otherwise null is returned and true_value
is not evaluated.
Evaluates and returns true_value
if condition
is true,
otherwise evaluates and returns false_value
.
The following IF
and CASE
expressions are equivalent:
SQL routines can use IF
statements that use a slightly
different syntax from IF
expressions. Specifically note the requirement
for terminating each clause with a semicolon ;
and the usage of END IF
.
COALESCE
Returns the first non-null value
in the argument list.
Like a CASE
expression, arguments are only evaluated if necessary.
NULLIF
Returns null if value1
equals value2
, otherwise returns value1
.
TRY
Evaluate an expression and handle certain types of errors by returning
NULL
.
In cases where it is preferable that queries 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
Examples
Source table with some invalid data:
Query failure without TRY
:
NULL
values with TRY
:
Query failure without TRY
:
Default values with TRY
and COALESCE
: