ADVERTISEMENT

SQL NULL Handling

In SQL, NULL represents a missing, undefined, or unknown value โ€” itโ€™s not the same as an empty string or zero. Understanding how to work with NULL is crucial to writing accurate queries.

๐Ÿ”น What is NULL?

  • NULL means no value or unknown.
  • Itโ€™s a placeholder โ€” not equal to anything, even another NULL.

๐Ÿ”น Checking for NULL

Use IS NULL and IS NOT NULL โ€” not = or !=.

-- Find rows where email is missing
SELECT * FROM users WHERE email IS NULL;

-- Find rows where email is present
SELECT * FROM users WHERE email IS NOT NULL;

๐Ÿ”น NULL and Comparison Operators

-- This will NOT return any results
SELECT * FROM users WHERE email = NULL;  -- โŒ Wrong

-- Use IS NULL instead
SELECT * FROM users WHERE email IS NULL;  -- โœ… Correct

๐Ÿ”น Handling NULL in Results

Use functions to deal with NULL values:

-- Replace NULL with a default value
SELECT COALESCE(phone, 'Not Provided') AS phone_display FROM users;

-- MySQL alternative: IFNULL(phone, 'N/A')
-- SQL Server alternative: ISNULL(phone, 'N/A')

๐Ÿ”น NULL in Aggregates

  • Aggregate functions like COUNT, AVG, SUM ignore NULLs (except COUNT(*) includes them).
SELECT COUNT(email) FROM users;         -- Ignores NULLs
SELECT COUNT(*) FROM users;             -- Counts all rows

๐Ÿง  Quick Recap

Key PointDescription
NULL MeaningUnknown or missing value
Check NULLUse IS NULL / IS NOT NULL
ComparisonsNULL = NULL is false! Use IS NULL
Replace NULLUse COALESCE, ISNULL, or IFNULL
AggregatesMost functions ignore NULLs

๐Ÿ’ก Always be mindful of NULLs โ€” they can silently break logic if not handled properly.

ADVERTISEMENT