๐ CASE WHEN & Conditional Logic
CASE WHEN is how you write if-then-else logic inside a SQL query. You use it to label rows, bucket values, replace missing data and count things conditionally, all without leaving SQL.
This tutorial covers CASE WHEN and its shorter cousins: IF(), COALESCE, NULLIF, NVL and NVL2.
Sample Data
We use the same employees view as in the introduction:
CREATE OR REPLACE TEMP VIEW employees AS
SELECT * FROM VALUES
(1, 'Asha', 'Engineering', 95000, DATE'2019-03-15', NULL, 'Bengaluru'),
(2, 'Ben', 'Engineering', 82000, DATE'2020-07-01', 1, 'Pune'),
(3, 'Chen', 'Sales', 60000, DATE'2021-01-10', 1, 'Mumbai'),
(4, 'Divya', 'Sales', 65000, DATE'2018-11-23', 3, 'Mumbai'),
(5, 'Elena', 'Marketing', 58000, DATE'2022-05-30', 1, NULL),
(6, 'Farid', 'Engineering', 82000, DATE'2023-02-14', 2, 'Bengaluru'),
(7, 'Grace', NULL, 45000, DATE'2024-01-08', NULL, 'Delhi')
AS employees(emp_id, name, dept, salary, hire_date, manager_id, city)
1. Searched CASE WHEN
The most common form checks a list of conditions from top to bottom and returns the value of the first one that is true:
-- Syntax
CASE
WHEN condition_1 THEN result_1
WHEN condition_2 THEN result_2
ELSE default_result
END
Here we put each employee into a salary band:
SELECT name,
salary,
CASE
WHEN salary >= 80000 THEN 'High'
WHEN salary >= 60000 THEN 'Medium'
ELSE 'Low'
END AS salary_band
FROM employees
ORDER BY salary DESC
+-----+------+-----------+
|name |salary|salary_band|
+-----+------+-----------+
|Asha |95000 |High |
|Ben |82000 |High |
|Farid|82000 |High |
|Divya|65000 |Medium |
|Chen |60000 |Medium |
|Elena|58000 |Low |
|Grace|45000 |Low |
+-----+------+-----------+
Every CASE must end with END. The AS salary_band after it names the new column, just like any other expression.
2. Simple CASE
When every condition compares the same column to a fixed value, you can use the shorter "simple" form. Put the column once after CASE, then list the values:
SELECT name,
dept,
CASE dept
WHEN 'Engineering' THEN 'ENG'
WHEN 'Sales' THEN 'SLS'
WHEN 'Marketing' THEN 'MKT'
ELSE 'Unassigned'
END AS dept_code
FROM employees
ORDER BY emp_id
+-----+-----------+----------+
|name |dept |dept_code |
+-----+-----------+----------+
|Asha |Engineering|ENG |
|Ben |Engineering|ENG |
|Chen |Sales |SLS |
|Divya|Sales |SLS |
|Elena|Marketing |MKT |
|Farid|Engineering|ENG |
|Grace|NULL |Unassigned|
+-----+-----------+----------+
The simple form only does equality checks. For ranges (>=), LIKE, or conditions on more than one column, use the searched form from section 1.
Common mistake:
CASE dept WHEN NULL THEN ...never matches, because the simple form compares with=andNULL = NULLis not true. Grace landed inELSEabove for exactly this reason. To test for NULL, use the searched form:CASE WHEN dept IS NULL THEN ....
3. No ELSE Means NULL
The ELSE branch is optional. If you leave it out and no condition matches, the result is NULL:
SELECT name,
salary,
CASE
WHEN salary >= 80000 THEN 'High'
END AS flag
FROM employees
ORDER BY emp_id
+-----+------+----+
|name |salary|flag|
+-----+------+----+
|Asha |95000 |High|
|Ben |82000 |High|
|Chen |60000 |NULL|
|Divya|65000 |NULL|
|Elena|58000 |NULL|
|Farid|82000 |High|
|Grace|45000 |NULL|
+-----+------+----+
Only Asha, Ben and Farid get High. Everyone else gets NULL, not an empty string. If a blank value would break something downstream, always write an explicit ELSE.
4. Order Matters: The First Match Wins
Spark stops at the first WHEN that is true. If you write the conditions in the wrong order, a broad condition can "swallow" rows meant for a narrower one:
SELECT name,
salary,
CASE
WHEN salary >= 60000 THEN 'Medium'
WHEN salary >= 80000 THEN 'High'
ELSE 'Low'
END AS salary_band
FROM employees
ORDER BY salary DESC
+-----+------+-----------+
|name |salary|salary_band|
+-----+------+-----------+
|Asha |95000 |Medium |
|Ben |82000 |Medium |
|Farid|82000 |Medium |
|Divya|65000 |Medium |
|Chen |60000 |Medium |
|Elena|58000 |Low |
|Grace|45000 |Low |
+-----+------+-----------+
Nobody is High. Asha's 95,000 is also >= 60000, so the first branch catches her and the second branch is never checked.
Rule of thumb: when the conditions overlap, put the most specific (narrowest) condition first. For ranges, that means going from the highest threshold down, as in section 1.
5. IF(): A Two-Way Shortcut
When there are only two outcomes, IF(condition, value_if_true, value_if_false) is a compact alternative to CASE:
SELECT name,
city,
IF(city = 'Mumbai', 'Mumbai office', 'Other') AS office
FROM employees
ORDER BY emp_id
+-----+---------+-------------+
|name |city |office |
+-----+---------+-------------+
|Asha |Bengaluru|Other |
|Ben |Pune |Other |
|Chen |Mumbai |Mumbai office|
|Divya|Mumbai |Mumbai office|
|Elena|NULL |Other |
|Farid|Bengaluru|Other |
|Grace|Delhi |Other |
+-----+---------+-------------+
Look at Elena. Her city is NULL, so city = 'Mumbai' is NULL, not true, and IF() returns the false value Other. A CASE WHEN behaves the same way: only a condition that is true picks its branch.
IF() is a Spark SQL function, so it is not portable to every database. CASE WHEN works everywhere, which is why many teams prefer it even for two branches.
6. COALESCE: The First Non-NULL Value
COALESCE(a, b, c, ...) returns the first argument that is not NULL. It is the standard way to fill in missing values:
SELECT name,
dept,
city,
COALESCE(dept, 'Unassigned') AS dept_filled,
COALESCE(city, dept, 'Unknown') AS location_hint
FROM employees
ORDER BY emp_id
+-----+-----------+---------+-----------+-------------+
|name |dept |city |dept_filled|location_hint|
+-----+-----------+---------+-----------+-------------+
|Asha |Engineering|Bengaluru|Engineering|Bengaluru |
|Ben |Engineering|Pune |Engineering|Pune |
|Chen |Sales |Mumbai |Sales |Mumbai |
|Divya|Sales |Mumbai |Sales |Mumbai |
|Elena|Marketing |NULL |Marketing |Marketing |
|Farid|Engineering|Bengaluru|Engineering|Bengaluru |
|Grace|NULL |Delhi |Unassigned |Delhi |
+-----+-----------+---------+-----------+-------------+
dept_filledkeeps the real department and only replaces Grace'sNULL.location_hinttriescityfirst. For Elena, whose city isNULL, it falls back to her department,Marketing.'Unknown'would only appear if both wereNULL.
COALESCE(x, y) is just a short way to write CASE WHEN x IS NOT NULL THEN x ELSE y END.
7. NULLIF: Turning a Value into NULL
NULLIF(a, b) returns NULL when a equals b, and a otherwise. Its most famous use is protecting a division from a zero denominator.
First, see what happens when you divide by zero. On Spark 3.5 with default settings, the result is quietly NULL:
SELECT 100 / 0 AS result
+------+
|result|
+------+
|NULL |
+------+
But many platforms turn on ANSI mode, which is the default in Spark 4.0 and Databricks SQL. With ANSI mode on, the same query fails:
SET spark.sql.ansi.enabled = true;
SELECT 100 / 0 AS result
[DIVIDE_BY_ZERO] Division by zero. Use `try_divide` to tolerate divisor being 0 and return NULL instead. If necessary set "spark.sql.ansi.enabled" to "false" to bypass this error.
NULLIF makes the query safe in both modes. If the denominator is 0, it becomes NULL, and anything divided by NULL is NULL instead of an error:
SET spark.sql.ansi.enabled = true;
SELECT team, wins, games,
wins / NULLIF(games, 0) AS win_rate
FROM VALUES ('Red', 6, 10), ('Blue', 0, 0) AS t(team, wins, games)
ORDER BY team
+----+----+-----+--------+
|team|wins|games|win_rate|
+----+----+-----+--------+
|Blue|0 |0 |NULL |
|Red |6 |10 |0.6 |
+----+----+-----+--------+
Team Blue has played no games, so its win_rate is NULL rather than a crash. The error message above also points to try_divide(wins, games), a Spark function that returns NULL for a zero divisor; NULLIF has the advantage of working in almost every SQL database. (We switch ANSI mode back off before the next section.)
SET spark.sql.ansi.enabled = false
+----------------------+-----+
|key |value|
+----------------------+-----+
|spark.sql.ansi.enabled|false|
+----------------------+-----+
8. NVL and NVL2
Spark also supports two Oracle-style functions:
| Function | Returns | Same as |
|---|---|---|
NVL(x, y) | x if it is not NULL, else y | COALESCE(x, y) |
NVL2(x, y, z) | y if x is not NULL, else z | CASE WHEN x IS NOT NULL THEN y ELSE z END |
SELECT name,
manager_id,
NVL(manager_id, 0) AS manager_or_zero,
NVL2(manager_id, 'Has manager', 'Top') AS reports_to
FROM employees
ORDER BY emp_id
+-----+----------+---------------+-----------+
|name |manager_id|manager_or_zero|reports_to |
+-----+----------+---------------+-----------+
|Asha |NULL |0 |Top |
|Ben |1 |1 |Has manager|
|Chen |1 |1 |Has manager|
|Divya|3 |3 |Has manager|
|Elena|1 |1 |Has manager|
|Farid|2 |2 |Has manager|
|Grace|NULL |0 |Top |
+-----+----------+---------------+-----------+
NVL2 is handy when you care whether a value exists, not what the value is. IFNULL(x, y) is another name for NVL(x, y).
9. Conditional Aggregation
This is the most useful CASE trick, and a favourite in interviews. Put a CASE inside an aggregate function to count or sum only some rows, while still producing one result row:
SELECT COUNT(*) AS total_staff,
SUM(CASE WHEN salary >= 80000 THEN 1 ELSE 0 END) AS high_earners,
COUNT(CASE WHEN dept = 'Sales' THEN 1 END) AS sales_staff,
SUM(CASE WHEN dept = 'Engineering' THEN salary END) AS eng_payroll
FROM employees
+-----------+------------+-----------+-----------+
|total_staff|high_earners|sales_staff|eng_payroll|
+-----------+------------+-----------+-----------+
|7 |3 |2 |259000 |
+-----------+------------+-----------+-----------+
How each column works:
SUM(CASE WHEN ... THEN 1 ELSE 0 END)adds 1 for every matching row, so the sum is a count.COUNT(CASE WHEN ... THEN 1 END)works because the missingELSEgivesNULL, andCOUNT(column)skips NULLs.SUM(CASE WHEN ... THEN salary END)adds up salary only for the matching rows.
Combined with GROUP BY, this turns rows into columns. Here we count, per department, how many people joined before and after 2021:
SELECT dept,
COUNT(CASE WHEN hire_date < DATE'2021-01-01' THEN 1 END) AS joined_before_2021,
COUNT(CASE WHEN hire_date >= DATE'2021-01-01' THEN 1 END) AS joined_2021_or_later
FROM employees
WHERE dept IS NOT NULL
GROUP BY dept
ORDER BY dept
+-----------+------------------+--------------------+
|dept |joined_before_2021|joined_2021_or_later|
+-----------+------------------+--------------------+
|Engineering|2 |1 |
|Marketing |0 |1 |
|Sales |1 |1 |
+-----------+------------------+--------------------+
Interview tip: "Count X and Y in one query without two scans" is almost always solved with conditional aggregation. Spark also has a shorter
COUNT(*) FILTER (WHERE ...)syntax, covered in GROUP BY & Aggregations.
10. CASE in ORDER BY: Custom Sort Orders
ORDER BY sorts text alphabetically. When the business wants a different order, sort by a CASE that maps each value to a number:
SELECT name, dept
FROM employees
ORDER BY CASE dept
WHEN 'Sales' THEN 1
WHEN 'Engineering' THEN 2
WHEN 'Marketing' THEN 3
ELSE 4
END,
name
+-----+-----------+
|name |dept |
+-----+-----------+
|Chen |Sales |
|Divya|Sales |
|Asha |Engineering|
|Ben |Engineering|
|Farid|Engineering|
|Elena|Marketing |
|Grace|NULL |
+-----+-----------+
Sales comes first, then Engineering, then Marketing, and the unassigned employee goes last. The second sort key, name, orders people within each department.
Try It in the Online Compiler
Copy this into the PySpark Online Compiler to try CASE WHEN and conditional aggregation yourself:
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName("Spark SQL CASE WHEN").getOrCreate()
spark.sql("""
CREATE OR REPLACE TEMP VIEW employees AS
SELECT * FROM VALUES
(1, 'Asha', 'Engineering', 95000, DATE'2019-03-15', NULL, 'Bengaluru'),
(2, 'Ben', 'Engineering', 82000, DATE'2020-07-01', 1, 'Pune'),
(3, 'Chen', 'Sales', 60000, DATE'2021-01-10', 1, 'Mumbai'),
(4, 'Divya', 'Sales', 65000, DATE'2018-11-23', 3, 'Mumbai'),
(5, 'Elena', 'Marketing', 58000, DATE'2022-05-30', 1, NULL),
(6, 'Farid', 'Engineering', 82000, DATE'2023-02-14', 2, 'Bengaluru'),
(7, 'Grace', NULL, 45000, DATE'2024-01-08', NULL, 'Delhi')
AS employees(emp_id, name, dept, salary, hire_date, manager_id, city)
""")
spark.sql("""
SELECT name, salary,
CASE WHEN salary >= 80000 THEN 'High'
WHEN salary >= 60000 THEN 'Medium'
ELSE 'Low' END AS salary_band,
COALESCE(dept, 'Unassigned') AS dept
FROM employees
ORDER BY salary DESC
""").show(truncate=False)
spark.sql("""
SELECT dept,
COUNT(CASE WHEN hire_date < DATE'2021-01-01' THEN 1 END) AS joined_before_2021,
COUNT(CASE WHEN hire_date >= DATE'2021-01-01' THEN 1 END) AS joined_2021_or_later
FROM employees
WHERE dept IS NOT NULL
GROUP BY dept
ORDER BY dept
""").show(truncate=False)
Summary
- A searched
CASE WHEN ... THEN ... ELSE ... ENDchecks conditions top to bottom and returns the first match. - The simple form
CASE col WHEN value THEN ...only does equality checks and never matchesNULL. - Without
ELSE, unmatched rows getNULL. Put narrow conditions before broad ones. IF(cond, a, b)is a two-way shortcut; aNULLcondition takes the false branch.COALESCE(andNVL/IFNULL) fill in NULLs;NVL2picks a value based on whether something is NULL.NULLIF(x, 0)turns a zero denominator intoNULL, which avoids divide-by-zero errors in ANSI mode.SUM(CASE ...)andCOUNT(CASE ...)count or sum subsets of rows in a single pass.
Next, you will look closely at NULL itself: how it behaves in comparisons, aggregates, joins and sorting.