Filtering and Sorting · Lesson 13 of 64

SQL NULL

What you will learn

  • What NULL is and what it is not
  • Why = NULL never works, and IS NULL instead
  • How NULL behaves in comparisons and in AND, OR, NOT
  • How COALESCE supplies a default and NULLIF creates a NULL

This lesson runs on the sample database you chose in lesson 1.1 (use the Example data picker at the top). Edit any query and press Run. Reset data puts the original rows back.

1. NULL is "no value"

NULL marks a missing value: unknown, or not applicable. It is not zero, not an empty text and not the word "null". You met it in lessons 1.3 and 1.5, where a calculation with NULL gave NULL. Database Fundamentals lesson 2.3 explains it in depth; here we use it in conditions.

Some columns in the sample databases can be NULL:

A customer's phone may be missing:

SELECT customer_id, first_name, phone FROM customers ORDER BY customer_id LIMIT 4;
customer_id  first_name  phone
-----------  ----------  ------------
          1  Vik         +35 49854883
          2  Wanda       NULL
          3  Dana        +58 13864688
          4  Noah        +48 26805141
(4 rows)

Few columns of the Bank may be empty. The note of an audit log entry may be missing:

SELECT log_id, action, note FROM audit_log ORDER BY log_id LIMIT 4;
log_id  action  note
------  ------  --------------
     1  update  NULL
     2  delete  NULL
     3  update  limit raised
     4  update  status changed
(4 rows)

A student's guardian_name may be missing:

SELECT student_id, first_name, guardian_name FROM students ORDER BY student_id LIMIT 4;
student_id  first_name  guardian_name
----------  ----------  -------------
         1  Vera        Amir Khan
         2  Elena       Nadia Haque
         3  Chloe       Mina Garcia
         4  Quinn       Femi Meyer
(4 rows)

2. = NULL does not work

Because NULL means "unknown", nothing is equal to it, not even another NULL. A comparison with NULL gives NULL (unknown), and WHERE keeps only rows where the condition is true:

SELECT NULL = NULL AS equal, NULL <> NULL AS not_equal, NULL = 5 AS compared_with_a_number, 5 = 5 AS normal;
equal  not_equal  compared_with_a_number  normal
-----  ---------  ----------------------  ------
NULL   NULL       NULL                         1
(1 row)
SELECT NULL = NULL AS equal, NULL <> NULL AS not_equal, NULL = 5 AS compared_with_a_number, 5 = 5 AS normal;
equal  not_equal  compared_with_a_number  normal
-----  ---------  ----------------------  ------
NULL   NULL       NULL                         1
(1 row)
SELECT NULL = NULL AS equal, NULL <> NULL AS not_equal, NULL = 5 AS compared_with_a_number, 5 = 5 AS normal;
equal  not_equal  compared_with_a_number  normal
-----  ---------  ----------------------  ------
NULL   NULL       NULL                         1
(1 row)

So WHERE phone = NULL finds nothing, even where the phone is missing:

SELECT COUNT(*) AS found FROM customers WHERE phone = NULL;
found
-----
    0
(1 row)
SELECT COUNT(*) AS found FROM audit_log WHERE note = NULL;
found
-----
    0
(1 row)
SELECT COUNT(*) AS found FROM students WHERE guardian_name = NULL;
found
-----
    0
(1 row)

3. IS NULL and IS NOT NULL

The correct test is IS NULL, and its opposite IS NOT NULL:

SELECT COUNT(*) AS without_phone FROM customers WHERE phone IS NULL;
SELECT COUNT(*) AS with_phone FROM customers WHERE phone IS NOT NULL;
without_phone
-------------
           84
(1 row)

with_phone
----------
       336
(1 row)
SELECT COUNT(*) AS without_note FROM audit_log WHERE note IS NULL;
SELECT COUNT(*) AS with_note FROM audit_log WHERE note IS NOT NULL;
without_note
------------
          29
(1 row)

with_note
---------
       91
(1 row)
SELECT COUNT(*) AS without_guardian FROM students WHERE guardian_name IS NULL;
SELECT COUNT(*) AS with_guardian FROM students WHERE guardian_name IS NOT NULL;
without_guardian
----------------
              38
(1 row)

with_guardian
-------------
          322
(1 row)

The two numbers add up to the whole table. That is a good habit: check that the parts add up.

4. NULL in <> and NOT

A row with a NULL is not kept by x <> 'a', because the comparison is unknown. Watch the totals:

SELECT COUNT(*) AS total FROM customers;
SELECT COUNT(*) AS phone_is_x FROM customers WHERE phone = '+35 49854883';
SELECT COUNT(*) AS phone_is_not_x FROM customers WHERE phone <> '+35 49854883';
total
-----
  420
(1 row)

phone_is_x
----------
         1
(1 row)

phone_is_not_x
--------------
           335
(1 row)
SELECT COUNT(*) AS total FROM audit_log;
SELECT COUNT(*) AS note_is_x FROM audit_log WHERE note = 'status changed';
SELECT COUNT(*) AS note_is_not_x FROM audit_log WHERE note <> 'status changed';
total
-----
  120
(1 row)

note_is_x
---------
       31
(1 row)

note_is_not_x
-------------
           60
(1 row)
SELECT COUNT(*) AS total FROM students;
SELECT COUNT(*) AS guardian_is_x FROM students WHERE guardian_name = 'Amir Khan';
SELECT COUNT(*) AS guardian_is_not_x FROM students WHERE guardian_name <> 'Amir Khan';
total
-----
  360
(1 row)

guardian_is_x
-------------
            2
(1 row)

guardian_is_not_x
-----------------
              320
(1 row)

"Is x" plus "is not x" do not add up to the total: the rows with NULL are in neither group. To include them, say so: WHERE column <> 'x' OR column IS NULL.

5. COALESCE: a default for NULL

COALESCE(a, b, ...) returns the first value that is not NULL. It is the usual way to replace a missing value:

SELECT customer_id, phone, COALESCE(phone, 'no phone') AS phone_to_show FROM customers ORDER BY customer_id LIMIT 4;
customer_id  phone         phone_to_show
-----------  ------------  -------------
          1  +35 49854883  +35 49854883
          2  NULL          no phone
          3  +58 13864688  +58 13864688
          4  +48 26805141  +48 26805141
(4 rows)
SELECT log_id, note, COALESCE(note, '(no note)') AS note_to_show FROM audit_log ORDER BY log_id LIMIT 4;
log_id  note            note_to_show
------  --------------  --------------
     1  NULL            (no note)
     2  NULL            (no note)
     3  limit raised    limit raised
     4  status changed  status changed
(4 rows)
SELECT student_id, guardian_name, COALESCE(guardian_name, 'not recorded') AS guardian_to_show FROM students ORDER BY student_id LIMIT 12;
student_id  guardian_name  guardian_to_show
----------  -------------  ----------------
         1  Amir Khan      Amir Khan
         2  Nadia Haque    Nadia Haque
         3  Mina Garcia    Mina Garcia
         4  Femi Meyer     Femi Meyer
         5  Ana Torres     Ana Torres
         6  Sam Patel      Sam Patel
         7  NULL           not recorded
         8  Gita Abdi      Gita Abdi
         9  NULL           not recorded
        10  Gita Torres    Gita Torres
        11  Priya Rahman   Priya Rahman
        12  Sam Sato       Sam Sato
(12 rows)

It also repairs calculations (lesson 1.3): COALESCE(discount, 0) treats a missing discount as zero.

6. NULLIF: make a NULL on purpose

NULLIF(a, b) returns NULL when the two values are equal, and a otherwise. It is handy to turn a placeholder such as an empty text into a real NULL, or to avoid dividing by zero:

SELECT NULLIF('', '') AS empty_to_null, NULLIF('x', '') AS stays, 10 / NULLIF(0, 0) AS safe_division;
empty_to_null  stays  safe_division
-------------  -----  -------------
NULL           x      NULL
(1 row)
SELECT NULLIF('', '') AS empty_to_null, NULLIF('x', '') AS stays, 10 / NULLIF(0, 0) AS safe_division;
empty_to_null  stays  safe_division
-------------  -----  -------------
NULL           x      NULL
(1 row)
SELECT NULLIF('', '') AS empty_to_null, NULLIF('x', '') AS stays, 10 / NULLIF(0, 0) AS safe_division;
empty_to_null  stays  safe_division
-------------  -----  -------------
NULL           x      NULL
(1 row)

Worked example: a count that adds up

A report says "customers with a phone: 336, without: 84, total: 420" and a colleague asks why the number of customers who do not have the phone +35 49854883 is 335 and not 419.

  1. Rows with a phone are 336; of these, one is +35 49854883, so 335 differ.
  2. The 84 rows without a phone are NULL; phone <> '+35 49854883' is unknown for them, so they are not counted.
  3. To count them too: WHERE phone <> '+35 49854883' OR phone IS NULL (419).

Whenever a total looks too small, ask whether NULL rows dropped out. The figures are from the Shop sample data.

Common mistakes

  • = NULL or <> NULL. Use IS NULL and IS NOT NULL.
  • Forgetting that <> drops the NULL rows.
  • Treating NULL as zero or as an empty text. It is neither.
  • NOT IN with a list that contains NULL (lesson 2.3).
  • Replacing NULL with a default silently. COALESCE hides that data was missing; say so in the report.

Key takeaways

  • NULL means no value; any comparison with it is unknown, so = NULL never matches.
  • Test with IS NULL and IS NOT NULL.
  • x <> 'a' and x = 'a' together miss the NULL rows.
  • COALESCE(a, b) gives the first non-NULL value; NULLIF(a, b) gives NULL when they are equal.

Practice

1. Which query finds customers with no phone?

Show answer

SELECT * FROM customers WHERE phone IS NULL;

2. What does SELECT NULL = NULL; return?

Show answer

NULL (unknown), not true.

3. What does COALESCE(NULL, NULL, 'x', 'y') return?

Show answer

'x', the first value that is not NULL.

4. Why might WHERE status <> 'open' miss some rows?

Show answer

Rows where status is NULL give an unknown result and are not kept. Add OR status IS NULL if they should be included.

5. What does NULLIF(5, 5) return?

Show answer

NULL, because the two values are equal.

6. How can you check that a count of IS NULL and IS NOT NULL rows is right?

Show answer

The two counts must add up to the total number of rows in the table.