What happened
In the provided SQLite example, a 10-row support-tickets table contains several null values across different columns like 'close time', 'region', and 'assignee'.
The query SELECT * FROM tickets WHERE assignee = NULL; is intended to retrieve all rows where the ‘assignee’ column has a null value. However, the result is zero rows returned – not the two unassigned tickets. This happens because of how SQL handles comparisons with NULL values.
Why it matters
The seemingly simple act of querying for nulls can lead to significant confusion and debugging headaches.
If a query returns an unexpected empty result, assuming that there isn’t a problem is rarely correct. Failing to accurately filter out rows based on the presence (or absence) of NULL values can completely skew your data analysis.
But, but, but…
The core issue stems from SQL's handling of comparisons with NULL. The = operator, when comparing against NULL, always evaluates to UNKNOWN, not true or false. This unknown result is then treated as a negative result by the WHERE clause, effectively filtering out all rows. The fix is simple: use WHERE column IS NULL instead of WHERE column = NULL.
The IS NULL operator specifically checks if a value is NULL, whereas = NULL tries to match a literal NULL value, which never happens. In essence, SQL treats an unknown comparison as 'no' – it’s a gate that only allows rows where the answer is definitively 'yes'. The original article included this table and code example for illustration: ``sql -- Ten tickets. Three are missing their close time, two are missing their region, and two have no assignee. ticket_id | region | minutes_to_close | assignee ---------- | ------ | ---------------- | -------- 1 | East | 45 | Priya 2 | East | NULL | Priya 3 | West | 30 | Marcus 4 | West | 90 | NULL 5 | NULL | 60 | Marcus 6 | East | 15 | Dana 7 | West | NULL | NULL 8 | NULL | 120 | Dana 9 | East | 75 | Priya 10 | West | NULL | Marcus ``
“A comparison in SQL can answer yes, no, or unknown, and that the WHERE gate lets only yes rows pass, so unknown rows disappear from the result exactly as if they had answered no.”
— Dr Non
The counter-take
The common misconception is that NULL represents 'zero' or ‘empty text’, leading developers to use = NULL as a search term. This approach invariably misses rows containing actual nulls, necessitating a shift in thinking about how SQL handles missing values.
The AI angle
AI development increasingly relies on datasets containing missing values; accurately querying for these nulls is foundational to building robust models that don't suffer from biased inferences—an upgrade in data understanding allows the use of more sophisticated AI techniques.
