Null-Safe Filtering in SQL
Comparisons against null return null, not true or false, so ordinary filters silently lose rows.
Here's a trap that produces wrong answers with no error. You ask for orders that didn't use a coupon code, write coupon_code <> 'SPRING10', and quietly lose every order that had no coupon at all.
The reason: comparing anything to NULL returns NULL, which a WHERE treats as "not true" and drops. IS DISTINCT FROM compares two values treating null as an ordinary value, so the null rows stay.
-- drops null rows unexpectedly
where plan <> 'pro'
-- null-safe: keeps null rows
where plan is distinct from 'pro'Schema · Garden ShopTable · orders6 columns · 24 rows
One row per order. Unshipped orders have a null shipped_date.
Find every order that did not use the coupon'SPRING10', including orders with no coupon at all. Return order_id and coupon_code, sorted byorder_id. Run the starter query first to see how many rows the naive <> filter misses.
- Columns: order_id, coupon_code.
- Rows: 21 orders (every order except the 3 that used SPRING10).
- Orders with no coupon (null) are included, which the naive <> filter drops.
You finished “Dates, Strings, and Nulls in Practice.”
Nice work. Ready to start the next one?
Start Chapter 8: DML: Measure Twice, Cut Once →Begins with 8.1 What is DML?