πŸ”Ž FilteringbeginnerCommonly used

How to handle NULL values in SQL

Check for, filter, and handle NULL values correctly.

Find rows with NULLAll databases
SELECT name, email
FROM users
WHERE phone IS NULL;

You must use IS NULL β€” never = NULL. NULL = NULL is always false in SQL.

Find rows without NULLAll databases
SELECT name, phone
FROM users
WHERE phone IS NOT NULL;

Returns only rows where phone has a value.

Replace NULL with a default (COALESCE)All databases
SELECT
  name,
  COALESCE(phone, 'No phone') AS phone
FROM users;

COALESCE returns the first non-NULL value. Useful for providing defaults.

When to use: Displaying data where NULL should show as a default value.

COALESCE with multiple fallbacksAll databases
SELECT
  name,
  COALESCE(mobile, phone, email, 'No contact') AS contact
FROM users;

Returns the first non-NULL value across multiple columns.

NULLIF β€” return NULL on a conditionAll databases
SELECT
  name,
  NULLIF(score, 0) AS score  -- returns NULL instead of 0
FROM users;

NULLIF(a, b) returns NULL if a = b, otherwise returns a. Useful to avoid division by zero.

When to use: NULLIF(total, 0) prevents division by zero: SUM(amount) / NULLIF(count, 0)

Common Mistakes

  • β†’Using = NULL instead of IS NULL β€” always use IS NULL / IS NOT NULL
  • β†’NOT IN with NULLs β€” NOT IN returns no rows if the list contains any NULL
  • β†’GROUP BY and ORDER BY treat NULLs as equal to each other
← Back to SQL Reference