Find a course

Module 2: Filtering RowsLesson 4 of 1113 min

NULL Values, CASE and Calculated Columns

Understand what NULL means, test for it with IS NULL, replace it with COALESCE, and build labeled columns with CASE expressions.

Step 1 of 16Learn

The value that is not a value

Look at the books table again. Quiet Numbers has NULL in the stock column. Tom Becker in the customers table has NULL as his email. NULL means the value is missing or unknown. It is not zero, not an empty string and not the word "NULL."

That difference matters. A stock of 0 means "we checked: none left." A stock of NULL means "we don't know how many." Treating the two the same leads to wrong reports.

NULL behaves in ways that surprise everyone at first. Any comparison with NULL produces unknown, not true or false, and WHERE keeps only rows where the condition is true. So:

SELECT title FROM books WHERE stock = NULL;   -- returns nothing!

returns zero rows, even though Quiet Numbers has a NULL stock. NULL is not equal to anything, not even another NULL. Instead, use the special operators:

SELECT title FROM books WHERE stock IS NULL;       -- Quiet Numbers
SELECT title FROM books WHERE stock IS NOT NULL;   -- the other 7

The unknown result causes subtler bugs too. This query finds books with fewer than 10 in stock:

SELECT title FROM books WHERE stock < 10;

It returns Gardens of Salt (0), Data in Practice (7), Learning to Cook (3) and The Last Signal (9): 4 rows. Now flip it to WHERE stock >= 10: The Silent Orbit, Night Ferry and River Road, 3 rows. That's 7 in total, not 8. Quiet Numbers fell through both filters, because "NULL < 10" is unknown, and so is "NULL >= 10."

Arithmetic with NULL also yields NULL: price * stock is NULL for Quiet Numbers.

Step 2 of 16Compare

NULL vs. 0 vs. empty text

AspectNULL0'' (empty text)
MeaningUnknown or missingA known number: zeroKnown text with no characters
ExampleStock never countedStock counted: none leftCustomer chose no nickname
Matched by = 0 or = ''?No, the comparison is unknownYes, stock = 0Yes, nickname = ''
How to find itIS NULL= 0= ''
In SUM / AVGIgnoredCounted as zeroNot numeric

Step 3 of 16Note

Step 4 of 16Practice · True or false

The condition WHERE email = NULL returns the customers whose email is missing.

Step 5 of 16Practice · Work it out

Using the customers table above, how many rows does this query return? SELECT name FROM customers WHERE email <> 'ava@example.com';

Step 6 of 16Note

Step 7 of 16Compare

Three-valued logic: AND and OR with UNKNOWN

Aspect… AND UNKNOWN… OR UNKNOWN
TRUEUNKNOWN (row dropped)TRUE (row kept)
FALSEFALSE (row dropped)UNKNOWN (row dropped)
UNKNOWNUNKNOWN (row dropped)UNKNOWN (row dropped)

Step 8 of 16Learn

Replacing NULLs with COALESCE

Often you want to show or use a fallback value instead of NULL. COALESCE returns the first non-NULL value from its list of arguments:

SELECT name, COALESCE(email, 'no email on file') AS contact
FROM customers;

Tom's row shows "no email on file"; everyone else shows their email.

COALESCE is especially useful in calculations:

SELECT title, price * COALESCE(stock, 0) AS stock_value
FROM books;

Now Quiet Numbers shows 0 instead of NULL. But think before you substitute. Is treating unknown stock as zero correct for this report? For a "value of inventory" report, it might understate inventory. Sometimes the honest output is to keep NULL, or to show the number of unknown values separately. COALESCE is a tool, not an automatic fix.

COALESCE can take several arguments: COALESCE(mobile_phone, work_phone, home_phone, 'none') returns the first phone number that exists.

Some databases have similar functions, such as IFNULL in MySQL and SQLite or ISNULL in SQL Server, but COALESCE is standard SQL and works almost everywhere.

A related function, NULLIF(a, b), returns NULL when a equals b. Its classic use is avoiding division by zero: total / NULLIF(quantity, 0) returns NULL instead of an error when quantity is 0.

Step 9 of 16Practice · Code challenge · SQL

Code challenge · SQL

One book has an unknown stock level. Return its title.

The starter runs without an error, but it returns no rows. Fix the condition.

The database for this exercise (tables and rows)
CREATE TABLE books (
  book_id INTEGER PRIMARY KEY,
  title   TEXT NOT NULL,
  author  TEXT NOT NULL,
  genre   TEXT,
  price   REAL,
  year    INTEGER,
  stock   INTEGER
);
INSERT INTO books VALUES
  (1, 'The Silent Orbit',  'Mara Quinn', 'Sci-Fi',  18.00, 2019, 12),
  (2, 'Gardens of Salt',   'Leo Park',   'Fiction', 15.50, 2021, 0),
  (3, 'Data in Practice',  'Ana Ruiz',   'Tech',    42.00, 2022, 7),
  (4, 'Night Ferry',       'Leo Park',   'Mystery', 12.99, 2017, 25),
  (5, 'Learning to Cook',  'Sam Odell',  'Food',    24.00, 2020, 3),
  (6, 'The Last Signal',   'Mara Quinn', 'Sci-Fi',  21.00, 2023, 9),
  (7, 'Quiet Numbers',     'Ana Ruiz',   'Tech',    35.00, 2018, NULL),
  (8, 'River Road',        'Jo Banks',   'Fiction', 14.00, 2016, 18);
Real SQLite, running in your browser on a fresh copy of the database.
  • Result matches the expected table

Step 10 of 16Practice · Fill in the blanks

Fill in the blanks

To find rows where a column has no value, write WHERE stock IS . To display a fallback such as 0 instead of a missing value, use the function (stock, 0).

Step 11 of 16Learn

Labeling rows with CASE

CASE adds if-then logic to a query. It checks conditions in order and returns the value for the first one that is true:

SELECT title, stock,
  CASE
    WHEN stock IS NULL THEN 'Unknown'
    WHEN stock = 0 THEN 'Sold out'
    WHEN stock < 10 THEN 'Low'
    ELSE 'In stock'
  END AS stock_status
FROM books;

Results: Gardens of Salt is "Sold out," Data in Practice, Learning to Cook and The Last Signal are "Low," Quiet Numbers is "Unknown," and the rest are "In stock."

Three details matter:

  1. Order of WHEN clauses. CASE stops at the first true condition. If WHEN stock < 10 came before WHEN stock = 0, a sold-out book would be labeled "Low," because 0 is less than 10.
  2. The NULL check comes first. Otherwise a NULL stock fails every comparison and falls to ELSE, wrongly labeled "In stock."
  3. ELSE is optional, but without it, rows matching no condition get NULL.

CASE works anywhere an expression is allowed: in SELECT, ORDER BY, and inside aggregate functions, a powerful pattern you'll see in the next module. For example, a price band:

SELECT title, price,
  CASE
    WHEN price < 15 THEN 'Budget'
    WHEN price < 30 THEN 'Standard'
    ELSE 'Premium'
  END AS price_band
FROM books;

Night Ferry and River Road are "Budget," Data in Practice and Quiet Numbers are "Premium," and the other four are "Standard."

Step 12 of 16Practice · Diagram

How CASE picks a label

CASE tests its WHEN conditions top to bottom and stops at the first true one. Tap each test.

Gardens of Salt has stock 0, which is also less than 10. At which test does CASE stop for it?

Tap the shape that answers the question, then press Check.

How CASE picks a labelProcess diagram: stock IS NULL? → 'Unknown' → stock = 0? → 'Sold out' → stock < 10? → 'Low' → ELSE → 'In stock'.stock ISNULL? →'Unknown'stock = 0? →'Sold out'stock < 10?→ 'Low'ELSE → 'Instock'
stock IS NULL? → 'Unknown'

Checked first, so Quiet Numbers is labeled Unknown before any comparison can misfire.

stock = 0? → 'Sold out'

Gardens of Salt stops here.

stock < 10? → 'Low'

Data in Practice (7), Learning to Cook (3), The Last Signal (9).

ELSE → 'In stock'

Everything left: The Silent Orbit, Night Ferry, River Road. Without ELSE, these would get NULL.

Step 13 of 16Practice · Code challenge · SQL

Code challenge · SQL

For every book with a known stock level, return the title and a calculated column stock_value = price × stock, sorted from the highest stock value to the lowest.

The row order is checked.

The database for this exercise (tables and rows)
CREATE TABLE books (
  book_id INTEGER PRIMARY KEY,
  title   TEXT NOT NULL,
  author  TEXT NOT NULL,
  genre   TEXT,
  price   REAL,
  year    INTEGER,
  stock   INTEGER
);
INSERT INTO books VALUES
  (1, 'The Silent Orbit',  'Mara Quinn', 'Sci-Fi',  18.00, 2019, 12),
  (2, 'Gardens of Salt',   'Leo Park',   'Fiction', 15.50, 2021, 0),
  (3, 'Data in Practice',  'Ana Ruiz',   'Tech',    42.00, 2022, 7),
  (4, 'Night Ferry',       'Leo Park',   'Mystery', 12.99, 2017, 25),
  (5, 'Learning to Cook',  'Sam Odell',  'Food',    24.00, 2020, 3),
  (6, 'The Last Signal',   'Mara Quinn', 'Sci-Fi',  21.00, 2023, 9),
  (7, 'Quiet Numbers',     'Ana Ruiz',   'Tech',    35.00, 2018, NULL),
  (8, 'River Road',        'Jo Banks',   'Fiction', 14.00, 2016, 18);
Real SQLite, running in your browser on a fresh copy of the database.
  • Result matches the expected table (rows in order)

Step 14 of 16Practice · Spot the mistake

This CASE expression should label sold-out books (stock 0) as "Sold out," books with fewer than 10 as "Low," unknown stock as "Unknown," and the rest as "In stock." Which lines cause wrong labels? Click them.

Step 15 of 16Practice · Sort into groups

Using the price band CASE expression from this lesson (under 15 Budget, under 30 Standard, otherwise Premium), sort each book.

Tap an item, then tap its group (or drag it there).

Step 16 of 16Practice · Choose one

Which expression shows each customer's email, or the text 'missing' when the email is NULL?