Thuta Learning
SQL
BasicData & DatabasesBeginner

NULL & Three-Valued Logic

SQLLesson 722 min

What you'll walk away with

  • Explain the difference between NULL, 0 and '' (empty text)
  • Explain that comparing with NULL gives UNKNOWN and that WHERE keeps only TRUE rows
  • Use IS NULL / IS NOT NULL instead of = NULL
  • Recognise how <> and NOT IN silently lose rows with NULLs, and fix it with IS DISTINCT FROM
  • Show a fallback value in place of NULL with COALESCE

Explain it simply

Explain it simply

Picture a class register where some students' email boxes are blank. Does the blank mean "has no email" or "nobody asked yet"? You cannot tell. SQL calls a value like that, missing or unknown, NULL.

The odd thing about NULL is that you can never say it "equals" anything, not even another NULL. Ask "is Su Su's email the same as Mya Mya's?" when neither is known, and the honest answer is "don't know". That is why SQL has a third answer, UNKNOWN, alongside TRUE and FALSE.

Problem → Why → Solution

The problem: searching for missing emails finds nobody

A school admin wants to text a reminder to every student who has not given an email yet, so they write the query below. Two students in the table have a NULL email, yet the result is (0 rows) and no error appears. The admin concludes everyone has filled in an email, and no reminders are sent.

missing-email.sql
SELECT name, phone
FROM students
WHERE email = NULL;   -- looks right, matches nothing
-- (0 rows)

Why are there zero rows?

email = NULL asks "is email equal to an unknown value?" That can never be answered, so on every row, whether email is filled in or NULL, the result is UNKNOWN. WHERE keeps only TRUE rows, so nothing survives. To test for a missing value you need the dedicated operator: WHERE email IS NULL.

Core concept: TRUE, FALSE and UNKNOWN

NULL is not a value but a marker meaning "no value / unknown". 0 is a number and '' is text with zero characters; neither is NULL. In the sample table, Kyaw Kyaw's email is '' (filled in, but empty) while Su Su's and Mya Mya's are NULL (never filled in). psql displays both as a blank, so they look identical on screen, but to the database they are completely different.

Every comparison (=, <>, <, >) and every arithmetic operation (+, *) involving NULL returns NULL; for a boolean result we call it UNKNOWN. AND, OR and NOT handle UNKNOWN by the rules below. The reasoning is simple: imagine UNKNOWN could be either TRUE or FALSE. If that could change the answer, the answer is UNKNOWN; if not, it is that fixed answer.

ExpressionResult
NULL = NULLUNKNOWN
TRUE AND UNKNOWNUNKNOWN
FALSE AND UNKNOWNFALSE (one FALSE decides it)
TRUE OR UNKNOWNTRUE (one TRUE decides it)
FALSE OR UNKNOWNUNKNOWN
NOT UNKNOWNUNKNOWN

WHERE keeps only rows where the condition is TRUE, discarding both FALSE and UNKNOWN rows. That is the root of every NULL bug. To test for NULL, use IS NULL and IS NOT NULL; these always return TRUE or FALSE, never UNKNOWN. When you want two NULLs to count as equal, PostgreSQL supports the SQL standard's IS DISTINCT FROM / IS NOT DISTINCT FROM (MySQL spells it <=>). To display a substitute for NULL, use COALESCE(a, b, ...), which returns its first argument that is not NULL.

truth-table.sql
SELECT NULL = NULL      AS null_eq_null,
       NULL IS NULL     AS null_is_null,
       (NULL AND FALSE) AS unknown_and_false,
       (NULL OR TRUE)   AS unknown_or_true;
-- psql shows:  (blank) | t | f | t
Mental model: WHERE only lets TRUE through
  1. Any comparison with NULL = UNKNOWN
  2. WHERE keeps only TRUE
  3. FALSE and UNKNOWN rows vanish
  4. Test for NULL with IS NULL

When rows go missing, first ask: could this column contain NULL?

General pattern

sql
WHERE col IS NULL                -- value is missing
WHERE col IS NOT NULL            -- value is present
WHERE col IS DISTINCT FROM val   -- NULL-safe "not equal"
SELECT COALESCE(col, fallback)   -- first non-NULL value

IS NULL and IS NOT NULL are the only correct way to test for NULL. IS DISTINCT FROM counts NULL as "different" too, and COALESCE substitutes a fallback wherever the value is NULL.

Example: = NULL versus IS NULL, side by side

The students table holds four students: Aung Aung (has an email), Su Su (email NULL), Kyaw Kyaw (email is '', empty text) and Mya Mya (email NULL). The two queries differ by a single operator, yet their results are completely different.

is-null.sql
-- Wrong: = NULL is never TRUE, so no row matches
SELECT name FROM students WHERE email = NULL;

-- Right: IS NULL finds the missing values
SELECT name FROM students WHERE email IS NULL;

Code breakdown

  1. Line 2SELECT name FROM students WHERE email = NULL;

    On all four rows email = NULL is UNKNOWN, so the result is (0 rows). The absence of any error is what makes this bug dangerous.

  2. Line 5SELECT name FROM students WHERE email IS NULL;

    IS NULL returns TRUE for Su Su and Mya Mya and FALSE for the other two, so two rows come back.

  3. Kyaw Kyaw

    Kyaw Kyaw's email is '', which is not NULL, so IS NULL skips him. Web forms often save a blank field as '', so "has no email" may need to cover both NULL and ''.

  4. Output

    The first query prints just a header and (0 rows); the second lists Su Su and Mya Mya.

You should see
 name
------
(0 rows)

  name
---------
 Su Su
 Mya Mya
(2 rows)
How WHERE decides one row
  1. Take the row
  2. Evaluate the condition (UNKNOWN if NULL is involved)
  3. Check whether the result is TRUE

TRUE

row kept in the result

FALSE / UNKNOWN

row dropped silently

The NULL trap in <> and NOT IN

Looking for "students whose email is not Aung Aung's" with email <> 'aung@example.com' returns only Kyaw Kyaw. Su Su and Mya Mya vanish because <> against their NULL email is UNKNOWN. When NULL should count as "different", use IS DISTINCT FROM.

distinct-from.sql
SELECT name
FROM students
WHERE email IS DISTINCT FROM 'aung@example.com';
-- Su Su, Kyaw Kyaw, Mya Mya

One NULL inside NOT IN

WHERE id NOT IN (1, NULL) returns no rows at all. NOT IN means id <> 1 AND id <> NULL, and id <> NULL is always UNKNOWN, so the whole AND can never be TRUE. Whenever you write NOT IN (SELECT ...), check whether that subquery can return a NULL.

In real projects

Where this shows up in real projects

In real databases NULL is everywhere: optional form fields nobody filled in, the shipped_at of an order that has not shipped, the deleted_at of a record that is still live. Conditions such as WHERE shipped_at IS NULL (orders still waiting) and the soft-delete filter WHERE deleted_at IS NULL appear in a huge number of production queries.

In reports, NULL quietly distorts numbers. A filter like discount <> 10 silently drops every order with no discount (NULL), and the sales total comes out too low. That is why experienced developers decide up front whether each column should be NOT NULL, and use fallbacks such as COALESCE(phone, 'not provided') when showing values on screen.

Common mistakes

Common mistakes

1. Writing = NULL or <> NULL

WHERE email = NULL and WHERE email <> NULL both return zero rows, with no error. Testing for NULL always means IS NULL or IS NOT NULL.

2. Treating NULL and '' as the same thing

If a form saves a blank as '' while an import script saves NULL, one table now has two ways to say "no email", and WHERE email IS NULL finds only half of them. Standardise on one (usually NULL); NULLIF(email, '') turns '' into NULL. (Oracle is the odd one out: it treats '' as NULL.)

3. Not realising a <> filter drops NULL rows

WHERE country <> 'UK' also removes rows whose country is unknown. If those rows belong in the result, write WHERE country IS DISTINCT FROM 'UK', or WHERE country <> 'UK' OR country IS NULL.

Best practices

Best practices

  • For every new column, ask whether its value can be unknown; if not, add NOT NULL.
  • Always include a NULL row and an '' row in test data and run every filter against them.
  • Agree as a team on one way to represent "no value", NULL or '', and stick to it.
  • Before writing NOT IN (SELECT ...), make sure the subquery's column cannot be NULL.

Mini challenge

Mini challenge: a student contact list

Using the students table (id, name, email, phone), write two queries.

  • First query: name and email of students whose email is not NULL
  • Second query: every student's name plus a contact column: the email if present, else the phone, else 'no contact'
  • Do not use = NULL or <> NULL
contacts.sql
-- TODO 1: students that have an email value (not NULL)

-- TODO 2: name + contact, falling back email -> phone -> 'no contact'
--   one function returns its first non-NULL argument

Expected: The first query returns Aung Aung and Kyaw Kyaw (his email is '' but not NULL, so he counts). The second shows aung@example.com, 09-222, a blank for Kyaw Kyaw (his '' wins) and no contact for Mya Mya.

Show hint

Use IS NOT NULL for the first query. In the second, COALESCE(email, phone, 'no contact') checks its arguments left to right and returns the first one that is not NULL.

Show solution
contacts.sql
SELECT name, email
FROM students
WHERE email IS NOT NULL;

SELECT name, COALESCE(email, phone, 'no contact') AS contact
FROM students;

Quick quiz 1 / 3

On the sample students table, who does WHERE email <> 'aung@example.com' return?

Quick quiz 2 / 3

What does SELECT NULL = NULL; return in PostgreSQL?

Quick quiz 3 / 3

How many rows does SELECT name FROM students WHERE id NOT IN (1, NULL); return?

What to remember

  • NULL is a marker for unknown or missing, not 0 and not ''.
  • Any comparison with NULL is UNKNOWN, and WHERE keeps only TRUE rows.
  • Test for NULL with IS NULL / IS NOT NULL; = NULL never matches.
  • <> and NOT IN silently drop NULL rows; consider IS DISTINCT FROM.
  • COALESCE returns the first non-NULL value and is the tool for fallbacks.

PostgreSQL SQL Tutorial — PostgreSQL Global Development Group

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

NULL & Three-Valued Logic | Thuta Learning