A technique for writing SQL CASE expressions that correctly evaluate and return values when NULLs are present.
The SQL CASE
expression is the Swiss-army knife of conditional logic in relational databases. Yet many practitioners struggle when NULL
values enter the picture. Because NULL
represents an unknown rather than an empty string or zero, comparisons that seem intuitive often return unexpected results. This article walks through the nuances of writing a CASE WHEN
statement that safely handles NULL
s, provides best practices, demonstrates real-world patterns, and highlights common pitfalls.
Incorrect NULL handling can silently corrupt business logic and analytics. A financial report that treats NULL revenue as zero will understate revenue, while a health-care application that misclassifies NULL test results may trigger false alarms. Because CASE
is frequently used to derive new fields, cleanse data, and build dimensional attributes, mastering NULL-aware patterns is critical for:
CASE
beats multiple nested queriesSQL operates under three-valued logic: TRUE
, FALSE
, and UNKNOWN
. Any comparison involving NULL
yields UNKNOWN
, which acts like FALSE
inside a CASE WHEN
branch. For example:
SELECT CASE WHEN NULL = 'foo' THEN 'match' END; -- returns NULL
The only safe way to test for NULL is IS NULL
(or IS NOT NULL
). Never rely on equality or inequality operators.
COALESCE(expr1, expr2, ...)
returns the first non-NULL expression, making it ideal for defaulting NULL to a sentinel value before comparison.
• Simple CASE: CASE expression WHEN value1 THEN ...
• Searched CASE: CASE WHEN condition THEN ...
Use searched CASE when you need IS NULL
checks.
CASE
WHEN amount IS NULL THEN 'Unknown'
WHEN amount < 0 THEN 'Negative'
WHEN amount = 0 THEN 'Zero'
ELSE 'Positive'
END AS amount_category
By checking amount IS NULL
first, you guarantee correct classification.
CASE
WHEN COALESCE(status, 'PENDING') = 'PENDING' THEN 0
ELSE 1
END AS is_complete
Here NULL
is transformed into 'PENDING'
before comparison, keeping the CASE logic simple.
Some engines such as MySQL offer <=>
(NULL-safe equal). Use cautiously because it is non-standard.
SUM(CASE WHEN return_date IS NULL THEN 1 ELSE 0 END) AS outstanding_orders
Counting NULLs accurately is a common requirement for service-level metrics.
Suppose we have an orders
table:
order_id | total_amount | shipped_at
-------- | ----------- | ----------
1 | 125.00 | 2024-01-08
2 | NULL | NULL
3 | -20.00 | 2024-02-01
We want a human-readable status:
SELECT order_id,
CASE
WHEN shipped_at IS NULL AND total_amount IS NULL THEN 'Pending & Amount Unknown'
WHEN shipped_at IS NULL THEN 'Pending Shipment'
WHEN total_amount < 0 THEN 'Refunded'
ELSE 'Completed'
END AS order_status
FROM orders;
The query correctly handles NULLs in both shipped_at
and total_amount
.
=
which fails on NULL.COALESCE
when the substitute value is logically sound.CASE WHEN column = NULL THEN 'Bad' END -- Always NULL
Fix: Replace with IS NULL
.
Without ELSE
, unmatched rows return NULL by default. Add an ELSE or ensure all possibilities are handled.
Putting broad conditions before NULL checks causes NULL rows to fall through unexpectedly. Order conditions from most specific to most general.
Galaxy’s modern SQL editor highlights NULL logic errors with inline linting. Type CASE WHEN col = NULL
and the AI copilot suggests replacing with IS NULL
. Collections let teams endorse the corrected query, ensuring company-wide best practices.
Handling NULLs in a CASE WHEN
statement is less about syntax and more about logical precision. Use searched CASE expressions, test vigorously, and leverage tooling like Galaxy to spot errors early. Master these patterns once, and you will prevent a class of silent, hard-to-trace bugs in every analytics or application stack you touch.
NULLs represent unknown data; mishandling them skews reports, metrics, and application logic. Because CASE is used everywhere—from ETL pipelines to dashboards—getting NULL handling right is essential for data integrity and reliable decision-making.
Because NULL stands for an unknown value. Any comparison with NULL yields UNKNOWN under SQL's three-valued logic. Use IS NULL instead.
You can, but only if you wrap the expression in COALESCE or use NULL-safe equality offered by some engines. Searched CASE is safer.
Galaxy's AI copilot flags risky patterns like = NULL
and suggests IS NULL. Its inline previews let you verify outputs with NULL test rows instantly.
They serve different purposes. Use COALESCE to default NULL to a value when that default is semantically valid; otherwise, keep explicit IS NULL checks for clarity.