Conditional logic & CASE
Concept  ·  SQL & Querying

Simple CASE compares with = so CASE x WHEN NULL never matches — the NULL arm is dead code and NULL rows fall to ELSE; only searched CASE sees them.

Simple CASE is sugar for a chain of x = value tests — and x = NULL is UNKNOWN, never TRUE, so the WHEN NULL arm is unreachable by construction. Nothing warns: the query is legal, the arm just never wins, and NULL rows quietly take the ELSE label — 'unknown' readings reported as 'normal'. The rule: the moment NULL is one of your cases, switch to searched CASE with WHEN x IS NULL first.

See it break
reads
sensormoisture
s1NULL
s21
The trap
SELECT
  sensor,
  CASE moisture
    WHEN NULL THEN 'missing'
    WHEN 1 THEN 'ok'
    ELSE 'other'
  END AS label
FROM
  reads
ORDER BY
  sensor;
The fix
SELECT
  sensor,
  CASE
    WHEN moisture IS NULL THEN 'missing'
    WHEN moisture = 1 THEN 'ok'
    ELSE 'other'
  END AS label
FROM
  reads
ORDER BY
  sensor;
INPUTYour queryThe fix
s1othermissing
s2okok

The NULL moisture sensor was labelled 'other' via ELSE — simple CASE tests with =, and moisture = NULL is UNKNOWN, so the WHEN NULL arm is dead code; only a searched CASE with WHEN moisture IS NULL sees it.

The rule

Searched CASE with the IS NULL arm first; simple CASE only over provably-non-null columns.

Shows up elsewhere
NULL = NULL is not TRUECASE takes the first match
Try one →Prove it in practice →