Working with NULL

Topic 4 of 4 in Querying a table12 min readBeginnerFree course

Overview

Real data is incomplete. A customer skips the optional phone field; a product hasn’t been given a category yet; an order hasn’t shipped, so it has no shipping date. SQL represents every one of these gaps with NULL.

NULL is simple to describe and easy to get wrong, because it doesn’t behave like a normal value. Most “my query is missing rows” mysteries in SQL come down to NULL. This lesson makes sure they don’t catch you.

What NULL means

NULL means unknown or not applicable. It’s a marker for the absence of a value, not a value itself:

  • NULL is not zero: a product with unknown stock is different from one with zero stock.
  • NULL is not an empty string: '' is a known piece of text that happens to be empty.
  • NULL is not false: it’s “we don’t know”.

psql shows NULL as an empty space, which looks exactly like an empty string. While you’re learning, it helps to make NULLs visible:

SQL
\pset null '(null)'
SELECT first_name, phone FROM customers WHERE id IN (2, 3);
Text
Null display is "(null)".
 first_name |      phone      
------------+-----------------
 Ben        | +44 7700 900123
 Chen       | (null)
(2 rows)

Chen’s phone is NULL. (\pset is a psql setting, not SQL; other tools usually show NULL in grey or italics.)

The = NULL trap

Here’s the mistake everybody makes once. To find customers without a phone, you might write:

SQL
SELECT first_name FROM customers WHERE phone = NULL;
Text
 first_name 
------------
(0 rows)

No rows — not an error, just nothing. Why? If a value is unknown, is it equal to another unknown value? Nobody can say. So phone = NULL evaluates to NULL — unknown — for every row, and WHERE only keeps rows where the condition is true.

The correct test is IS NULL:

SQL
SELECT first_name FROM customers WHERE phone IS NULL;
Text
 first_name 
------------
 Chen
 Elena
 Hugo
 Jack
(4 rows)

And its opposite, IS NOT NULL:

SQL
SELECT first_name, phone FROM customers WHERE phone IS NOT NULL;
Text
 first_name |       phone       
------------+-------------------
 Asha       | +91 98200 11223
 Ben        | +44 7700 900123
 Dee        | +234 803 555 0101
 Farhan     | +91 99870 44556
 Grace      | +1 206 555 0147
 Isha       | +91 98111 77889
(6 rows)

You can see the trap directly by selecting the comparisons:

SQL
SELECT NULL = NULL   AS equals,
       NULL <> NULL  AS not_equals,
       NULL IS NULL  AS is_null,
       1 = NULL      AS one_equals_null;
Text
 equals | not_equals | is_null | one_equals_null 
--------+------------+---------+-----------------
        |            | t       | 
(1 row)

Three NULLs and one t. Only IS NULL gives a definite answer.

NULL spreads

Almost any calculation that involves NULL produces NULL. If you don’t know one of the numbers, you can’t know the total:

SQL
SELECT 5 + NULL        AS sum,
       NULL * 0        AS product,
       'Tea' || NULL   AS joined,
       upper(NULL)     AS shouted;
Text
 sum | product | joined | shouted 
-----+---------+--------+---------
     |         |        | 
(1 row)

Even NULL * 0 is NULL. Watch for this in calculated columns: a single NULL input makes the whole result NULL, and a total of a column that contains NULLs needs care (aggregate functions handle this by skipping NULLs — see Aggregate functions).

Three-valued logic

Because comparisons can return unknown, SQL logic has three values: TRUE, FALSE and NULL (unknown). AND, OR and NOT follow common-sense rules — think of NULL as “could be either”:

NULL and three-valued logic. The AND table: TRUE AND TRUE is TRUE; anything AND FALSE is FALSE; TRUE AND NULL is NULL; NULL AND NULL is NULL. The OR table: anything OR TRUE is TRUE; FALSE OR FALSE is FALSE; FALSE OR NULL is NULL; NULL OR NULL is NULL. NULL means unknown: NULL = NULL gives NULL, NULL <> 1 gives NULL, 5 + NULL gives NULL, and NOT NULL gives NULL. Any comparison with NULL is NULL, not TRUE or FALSE, so WHERE phone = NULL never matches. Test for missing values with IS NULL or IS NOT NULL; compare NULL-safely with IS DISTINCT FROM; replace NULL with a fallback using COALESCE(phone, ‘no phone’). WHERE phone = NULL is never true and returns 0 rows; WHERE phone IS NULL is the right way and returns Chen, Elena, Hugo and Jack.

  • FALSE AND unknown is FALSE — whatever the unknown is, the result is false.
  • TRUE OR unknown is TRUE — one true side is enough.
  • TRUE AND unknown and FALSE OR unknown stay unknown.

This explains a puzzle. The gift card has a NULL category. Which products are not in category 1?

SQL
SELECT name, category_id
FROM products
WHERE category_id <> 1;
Text
          name          | category_id 
------------------------+-------------
 Darjeeling First Flush |           2
 Assam Breakfast        |           2
 Jasmine Green          |           2
 Chamomile Calm         |           2
 Pour-Over Dripper      |           3
 Burr Grinder           |           3
 Electric Kettle        |           3
 Glass Teapot           |           3
(8 rows)

Eight products — the gift card is missing. NULL <> 1 is unknown, so the row is dropped. If you want “everything that isn’t coffee, including things with no category”, say so:

SQL
SELECT name, category_id
FROM products
WHERE category_id <> 1 OR category_id IS NULL;
Text
          name          | category_id 
------------------------+-------------
 Darjeeling First Flush |           2
 Assam Breakfast        |           2
 Jasmine Green          |           2
 Chamomile Calm         |           2
 Pour-Over Dripper      |           3
 Burr Grinder           |           3
 Electric Kettle        |           3
 Glass Teapot           |           3
 Gift Card              |            
(9 rows)

Rule: whenever you filter with <>, NOT IN or NOT, ask yourself, “what should happen to rows where this column is NULL?”

IS DISTINCT FROM: NULL-safe comparison

a IS DISTINCT FROM b works like <>, except that it treats two NULLs as equal and NULL versus a value as different. It always returns true or false, never NULL:

SQL
SELECT name, category_id
FROM products
WHERE category_id IS DISTINCT FROM 1;
Text
          name          | category_id 
------------------------+-------------
 Darjeeling First Flush |           2
 Assam Breakfast        |           2
 Jasmine Green          |           2
 Chamomile Calm         |           2
 Pour-Over Dripper      |           3
 Burr Grinder           |           3
 Electric Kettle        |           3
 Glass Teapot           |           3
 Gift Card              |            
(9 rows)

Nine rows, gift card included. IS NOT DISTINCT FROM is the NULL-safe version of =. These are especially useful when comparing two columns that might both be NULL — “has this value changed?”.

COALESCE: a fallback value

COALESCE(a, b, c, …) returns the first argument that isn’t NULL. It’s the standard way to replace a missing value with a default:

SQL
SELECT first_name,
       COALESCE(phone, 'no phone') AS phone
FROM customers
WHERE country IN ('India', 'Singapore');
Text
 first_name |      phone      
------------+-----------------
 Asha       | +91 98200 11223
 Chen       | no phone
 Farhan     | +91 99870 44556
 Isha       | +91 98111 77889
(4 rows)

It accepts any number of arguments, so COALESCE(mobile, landline, email) means “the best contact we have”. All arguments must be of compatible types — COALESCE(category_id, 'none') fails because one is an integer and the other text; use COALESCE(category_id::text, 'none').

NULLIF: turning a value into NULL

NULLIF(a, b) returns NULL if a equals b, otherwise a. That sounds odd until you need it. The classic use is avoiding division by zero. Here’s a made-up ratio that divides each coffee’s price by its stock level:

SQL
SELECT name, price, stock,
       price / stock AS ratio
FROM products
WHERE category_id = 1;
Text
ERROR:  division by zero

One product with zero stock breaks the whole query. With NULLIF, a zero becomes NULL and the division quietly gives NULL for that row:

SQL
SELECT name, price, stock,
       round(price / NULLIF(stock, 0), 4) AS ratio
FROM products
WHERE category_id = 1;
Text
         name          | price | stock | ratio  
-----------------------+-------+-------+--------
 Ethiopian Yirgacheffe | 14.50 |    40 | 0.3625
 Colombian Supremo     | 12.00 |    55 | 0.2182
 Decaf House Blend     | 11.25 |     0 |       
(3 rows)

It’s also handy for cleaning data, such as treating empty strings as missing: NULLIF(phone, '').

NULLs elsewhere in SQL

You’ll meet NULL again throughout the course:

  • Sorting: NULLs sort last ascending and first descending in PostgreSQL (Sorting and limiting).
  • Aggregates: count(phone), sum, avg and friends ignore NULLs; count(*) counts rows (Aggregate functions).
  • Outer joins produce NULLs for rows without a match (Outer joins).
  • NOT IN with a NULL in the list returns no rows at all (EXISTS and correlated subqueries).
  • Constraints: NOT NULL stops NULLs getting into a column in the first place (Constraints and keys).

Design tip: NULLs are unavoidable, but you can limit them. When a column should always have a value — an order’s status, a product’s price — declare it NOT NULL, and the database will refuse rows that leave it empty.

Exercise

How do we reach each customer?

Support wants a contact list. First, write a query returning the first_name and email of every customer who has no phone number, sorted by first name (you should get Chen, Elena, Hugo and Jack). Then write a second query returning every customer's first_name and a column named contact that shows their phone number, or their email address if they have no phone — sorted by id.

SQL
-- 1. Customers with no phone number
SELECT first_name, email
FROM customers;

-- 2. Phone if we have one, otherwise email

Summary

  • NULL means a value is missing or unknown; it is not zero, not an empty string and not false.
  • Any comparison with NULL — even NULL = NULL — gives NULL (unknown), so WHERE x = NULL never matches. Use IS NULL and IS NOT NULL.
  • Arithmetic and most functions return NULL if any input is NULL.
  • SQL uses three-valued logic: TRUE, FALSE and UNKNOWN. WHERE keeps only TRUE rows.
  • COALESCE(a, b, …) returns the first non-NULL value; NULLIF(a, b) turns a value into NULL; IS DISTINCT FROM compares NULL-safely.