Q7 of 26 · SQL

How do you find rows with NULL values in a specific column, and why can't you use = NULL?

SQLJuniorsqlnullis-nulldata-integrity

Short answer

Short answer: Use IS NULL (not = NULL). NULL represents the absence of a value; SQL's equality operator cannot compare to 'unknown', so = NULL always evaluates to unknown, never true.

Detail

NULL in SQL is not a value — it's the absence of a value. Because of this, the equality operator = doesn't work:

-- This returns NO rows, even if shipped_at has NULLs
SELECT * FROM orders WHERE shipped_at = NULL;   -- WRONG

-- Correct
SELECT * FROM orders WHERE shipped_at IS NULL;
SELECT * FROM orders WHERE shipped_at IS NOT NULL;

QA uses:

  • Verify that a required column isn't NULL after an INSERT:
    SELECT COUNT(*) FROM orders WHERE customer_id IS NULL;
    -- Expect 0
    
  • Find records that should have been populated but weren't (e.g., order confirmation emails not sent):
    SELECT order_id, created_at FROM orders
    WHERE  confirmation_sent_at IS NULL
      AND  status = 'confirmed';
    

NULL also propagates through arithmetic: any expression involving NULL returns NULL. Be aware when summing or averaging columns that may have NULLs — use COALESCE(col, 0) to substitute a default.

// WHAT INTERVIEWERS LOOK FOR

Knowing IS NULL vs = NULL and why. A concrete example of using it as a data-integrity check.