Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 18/ 160
01. SQL Foundations & Relational Concepts

Handling NULL Values (IS NULL, IS NOT NULL, Three-Valued Logic)

Reason about NULL with three-valued logic and avoid = NULL mistakes.

IntermediateNULL · IS NULL · 3VL3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

NULL means "we don't know". Comparing anything with "we don't know" gives "we don't know", and SQL drops those rows from a WHERE.

Think of it like…

Ask "is the unknown person taller than 170 cm?" The honest answer isn't yes or no; it's "I don't know". SQL answers UNKNOWN, and WHERE leaves the row out.

Where you’ve seen it

SELECT * FROM users WHERE country <> 'IN' silently excludes every user whose country is NULL. If 15% of signups skipped the country field, your "users outside India" report is 15% short.

Words you’ll hear

NULL
A missing or unknown value. Not 0, not ''.
Three-valued logic
Conditions evaluate to TRUE, FALSE or UNKNOWN.
IS NULL / IS NOT NULL
The only correct way to test for NULL.
IS DISTINCT FROM
NULL-safe comparison that treats two NULLs as equal (MySQL: <=>).

Visual diagram

Loading interactive diagram

Theory & example queries

Three-valued logic in WHERE, AND and OR

WHERE keeps a row only when its condition is TRUE. FALSE and UNKNOWN are both dropped, which is why WHERE col = NULL never returns anything. Use col IS NULL.

UNKNOWN combines predictably: TRUE OR UNKNOWN is TRUE and FALSE AND UNKNOWN is FALSE, but almost everything else involving UNKNOWN stays UNKNOWN. NOT UNKNOWN is still UNKNOWN, so negating a condition doesn't bring NULL rows back.

Including NULLs explicitly

WHERE country <> 'IN' OR country IS NULL, or in PostgreSQL WHERE country IS DISTINCT FROM 'IN'.

Key takeaway: WHERE keeps TRUE only; UNKNOWN rows silently disappear.

Where NULLs bite: aggregates, NOT IN and joins

COUNT(*) counts rows; COUNT(col) counts non-NULL values. AVG(rating) divides by the number of non-NULL ratings, not total rows, which is often what you want but worth saying out loud. SUM over only NULLs is NULL, not 0, so reports usually wrap it: COALESCE(SUM(x), 0).

x NOT IN (subquery) returns no rows at all if the subquery contains a single NULL, because x <> NULL is UNKNOWN. Use NOT EXISTS instead. In joins, ON a.key = b.key never matches NULL keys, so rows with a NULL join key fall out of inner joins.

The NOT IN trapQuery example
1Input dataStart from the source rows or state that the statement sees.
customers
3 rows
customers sample rows
idnameemailcity
1Mayamaya@example.comPune
2Raviravi@example.comDelhi
3Noornoor@example.comMumbai
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  *3FROM4  customers5WHERE6  id NOT IN (7    SELECT8      customer_id9    FROM10      orders11  )
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/11
3OutputInspect the representative rows, affected-row count, plan, or command status.
Result of NOT IN with a NULL0 rows returned
Result of NOT IN with a NULL
idnameemail
No rows returned

Note: No rows are returned if the orders subquery contains a NULL customer_id, even when matching customer rows exist. Column names are illustrative for a SELECT * over customers.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

returns nothing if any order has a NULL customer_id. WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id) is correct.

Key takeaway: Prefer NOT EXISTS over NOT IN, and COALESCE the sums you report.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Schema

Find the nullable columns

Check which columns allow NULL (no NOT NULL constraint). Those are the ones every filter, join and aggregate has to account for, and it's worth asking what NULL means in each.

Focus at this step

information_schema.columns.is_nullable

What to watch at this step
Ask
what does NULL mean here?
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

NULL means *unknown or missing*, not zero and not an empty string. Any comparison with NULL, even NULL = NULL, returns UNKNOWN, and WHERE only keeps rows where the condition is TRUE. That's three-valued logic: TRUE, FALSE and UNKNOWN.

Why it matters: NULLs cause silently wrong answers rather than errors: rows vanish from WHERE col <> 'x', NOT IN returns nothing, averages skip rows and joins drop matches. Interviewers use NULL questions to separate people who have debugged real data from people who haven't.

When to reach for it

  • Reports where missing values must be counted or labelled
  • Change detection between two tables (old vs new value)
  • Anti-joins: finding rows that have no match

When to avoid or be careful

  • = NULL or <> NULL comparisons
  • NOT IN against a subquery whose column can be NULL
  • COALESCE-ing everything to 0 so missing data looks like real zeros

Ways to handle NULL

IS NULL / IS NOT NULL
Best for: Filtering missing values

Strengths: Correct and readable; most engines can use an index for it.

Watch out: Has to be added explicitly to "not equal" filters.

COALESCE(col, default)
Best for: Display values and arithmetic

Strengths: Turns NULL into a usable value.

Watch out: Can hide missing data in reports, and wrapping an indexed column in WHERE can stop the index being used.

IS DISTINCT FROM
Best for: Comparing two columns that may both be NULL (change detection)

Strengths: Treats NULL = NULL as equal and never returns UNKNOWN.

Watch out: Not available in every dialect (MySQL uses <=>).

Interview signals & numbers to know

When this topic comes up

  • “Why does my query return fewer rows than expected?”
  • NOT IN returns nothing
  • COUNT(*) vs COUNT(column)
  • AVG with missing values
  • Three-valued logic

Benchmarks & rules of thumb

3 -
truth values: TRUE, FALSE, UNKNOWN
NULL = NULL -
UNKNOWN
SUM of only NULLs -
NULL, not 0

Common mistakes & follow-ups

Common interview mistakes

  • Writing WHERE col = NULL and getting zero rows.
  • Using NOT IN against a subquery that contains NULLs.
  • Forgetting that col <> 'x' also excludes the rows where col is NULL.

Likely interviewer follow-ups

  • Why does NOT IN return no rows when the subquery contains a NULL, while NOT EXISTS works?
  • What is the difference between COUNT(*), COUNT(col) and COUNT(DISTINCT col)?
  • How do NULLs behave in GROUP BY and in a UNIQUE constraint?
Interview tip: Lead with "NULL means unknown, so comparisons return UNKNOWN and WHERE drops those rows", then give the NOT IN example. It's usually the one the interviewer is fishing for.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Handling NULL Values (IS NULL, IS NOT NULL, Three-Valued Logic) with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Pattern Matching (LIKE, ILIKE, Wildcards % and _)
Next topic
Sorting & Limiting Results (ORDER BY, ASC/DESC, LIMIT, OFFSET)