Skip to content
Back to 50 Concepts
Topic 16 of 50foundationsBeginner

# Topic 16: IS NULL & NULL Handling

Three-Valued Logic (3VL), IS NULL, IS NOT NULL, COALESCE, NULLIF, and avoiding = NULL errors.

1. Definition

In SQL, NULL represents missing, unknown, or inapplicable information. Because it is not a concrete value, it cannot be evaluated with equality operators (=, !=) and requires IS NULL or IS NOT NULL.

Relational Invariant:Deterministic relational algebra contract evaluated by the Cost-Based Optimizer.

2. Explain Like I'm 5

Intuitive mental model for beginners

NULL is an empty mystery box. You cannot ask "Does box A equal box B?" because nobody knows what is inside either box. You can only ask "Is this box empty?".

3. Animation & Visual Simulation

Interactive Engine Trace
Interactive Engine Simulation

IS NULL & NULL Handling Visual Simulator

Step 1 of 3
SQL>SELECT name, COALESCE(bio, 'No bio added.') AS bio FROM profiles WHERE deleted_at IS NULL;Active Input

Step 1: Input & Parsing Stage

Engine Action: Validate SQL syntax and resolve schema metadata for IS NULL & NULL Handling
SQL Input

Initiating IS NULL & NULL Handling

Schema Catalog

Checking Table Invariants

How the Database Executes This:

The database engine inspects active tables, verifies permissions, and prepares the physical operation.

💡 Empty Gift Box: You cannot tell if two unmarked closed boxes hold the same present. They are both UNKNOWN until inspected.

4. Real-World Example

An application tracks user phone numbers, where some users have not provided a number yet.

Users
idnamephone_number
1Lucky9876543210
2RahulNULL (Unknown)
Relational walkthrough: WHERE phone_number = NULL returns ZERO rows! You must write WHERE phone_number IS NULL.

5. SQL Syntax

ANSI SQL / PostgreSQL Dialect
Step 1: Proper NULL checks
-- INCORRECT (Always returns 0 rows!):
-- SELECT * FROM users WHERE phone_number = NULL;

-- CORRECT:
SELECT id, name FROM users WHERE phone_number IS NULL;
SELECT id, name FROM users WHERE phone_number IS NOT NULL;
Step 2: Fallback with COALESCE
SELECT name, COALESCE(phone_number, 'Not Provided') AS contact_phone
FROM users;
COALESCE returns the first non-null argument in the parameter list.
Step 3: Preventing division by zero with NULLIF
SELECT total_sales / NULLIF(total_orders, 0) AS avg_sale FROM stats;
NULLIF(x, 0) turns 0 into NULL, which safely causes division to return NULL instead of crashing.

6. Important Rules & Behaviors

RuleBehavioral Explanation
No Equality with NULLNULL = NULL evaluates to UNKNOWN, not TRUE.
WHERE Clause FilterA WHERE predicate only admits rows evaluating strictly to TRUE; UNKNOWN rows are discarded.
IS DISTINCT FROMcol IS DISTINCT FROM val safely handles NULL as a comparable value in PostgreSQL.
Three-Valued Logic (3VL)Comparisons with NULL yield UNKNOWN. UNKNOWN is treated as false in WHERE, but groups together in GROUP BY.
COALESCE vs NULLIF semanticsCOALESCE returns the first non-null argument; NULLIF returns NULL if two arguments are equal.

7. Deep Dive: Aggregate Functions and NULLs

Standard aggregate functions like COUNT(column), SUM(column), and AVG(column) completely ignore NULL values! Notice that COUNT(*) counts physical rows, but COUNT(column) only counts rows where that specific column is NOT NULL.

-- Table with 3 rows: values [10, 20, NULL]
SELECT
  COUNT(*) AS total_rows,      -- Returns 3
  COUNT(val) AS non_null_rows,  -- Returns 2
  AVG(val) AS average           -- Returns 15 ((10 + 20) / 2, not 30/3!)
FROM numbers;
Caution: AVG() ignores NULLs, which can artificially skew statistical metrics unless wrapped with COALESCE(val, 0).

8. Advantages & Disadvantages

Advantages

  • •Cleanly represents unknown or optional real-world attributes.
  • •COALESCE provides seamless fallback defaults.

Disadvantages & Trade-offs

  • •Three-Valued Logic introduces subtle bugs if developers use = NULL.

9. Common Interview Questions

Q1.Why does "WHERE col = NULL" always return zero rows in SQL?

In relational database theory and ANSI SQL, NULL represents missing, unknown, or inapplicable information. You cannot say whether an unknown value is equal to another unknown value. Therefore, the expression col = NULL evaluates to UNKNOWN. The WHERE clause only returns rows where the filter evaluates to TRUE, so all rows are discarded. You must use IS NULL.

Q2.What is Three-Valued Logic (3VL) and how do truth tables work with UNKNOWN?

SQL uses 3VL with three truth values: TRUE, FALSE, and UNKNOWN. Key truth table rules: TRUE AND UNKNOWN = UNKNOWN, FALSE AND UNKNOWN = FALSE (short-circuits), TRUE OR UNKNOWN = TRUE (short-circuits), FALSE OR UNKNOWN = UNKNOWN, NOT UNKNOWN = UNKNOWN. In WHERE/HAVING filters, only TRUE qualifies; UNKNOWN is rejected.

Q3.What is the difference between COALESCE and NULLIF?

COALESCE takes N arguments and returns the first non-NULL expression: COALESCE(phone, mobile, 'N/A'). NULLIF takes two arguments and returns NULL if they are equal, otherwise returning the first argument: NULLIF(val, 0) is commonly used to prevent division-by-zero errors (e.g. total / NULLIF(count, 0)).

Q4.How do B-Tree indexes handle NULL values across PostgreSQL, MySQL, and Oracle?

In PostgreSQL and MySQL (InnoDB), B-Tree indexes index NULL values. A query with WHERE col IS NULL can utilize an Index Scan. In Oracle, B-Tree indexes completely omit entries where ALL indexed columns are NULL, meaning Oracle cannot use a single-column B-Tree index for WHERE col IS NULL unless a compound index or bitmap index is used.

Q5.How does GROUP BY and ORDER BY treat NULL values?

In GROUP BY, all NULL values are considered equal and collapsed into a single distinct group bucket. In ORDER BY, ANSI SQL allows specifying NULLS FIRST or NULLS LAST: in PostgreSQL, NULLs default to NULLS LAST for ASC and NULLS FIRST for DESC; in MySQL, NULLs are treated as the lowest possible values.

10. Interview-Ready Answer

“NULL represents missing data and requires Three-Valued Logic. Equality checks (= NULL) fail because comparisons with NULL evaluate to UNKNOWN. Use IS NULL, IS NOT NULL, and COALESCE to handle nullability safely.”

11. Quick Test

Scenario Question:

What is the result of the expression: NULL = NULL?

Select your answer: