Conditional Expressions¶
This page documents conditional expressions available in Polars SQL.
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:
CASE expression
WHEN value THEN result
[ WHEN ... ]
[ ELSE result ]
END
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:
SELECT a,
CASE a
WHEN 1 THEN 'one'
WHEN 2 THEN 'two'
ELSE 'many'
END
The “searched” form evaluates each boolean condition from left
to right until one is true and returns the matching result:
CASE
WHEN condition THEN result
[ WHEN ... ]
[ ELSE result ]
END
If no conditions are true, the result from the ELSE clause is
returned if it exists, otherwise null is returned. Example:
SELECT a, b,
CASE
WHEN a = 1 THEN 'aaa'
WHEN b = 2 THEN 'bbb'
ELSE 'ccc'
END
IF¶
The IF expression is equivalent to a single-condition CASE
expression:
CASE
WHEN condition THEN true_value
[ ELSE false_value ]
END
- if(condition, true_value)¶
Evaluates and returns
true_valueifconditionis true, otherwise null is returned.
- if(condition, true_value, false_value)
Evaluates and returns
true_valueifconditionis true, otherwise evaluates and returnsfalse_value.
COALESCE¶
- coalesce(value[, ...])¶
Returns the first non-null
valuein the argument list. At least one argument is required.
NULLIF¶
- nullif(value1, value2)¶
Returns null if
value1equalsvalue2, otherwise returnsvalue1.