NULL Values: Beginner
One table, 3 kinds of nothing
A shop keeps a products table. stock is an INTEGER counting units on the shelf, and description is a VARCHAR that the seller types into a form.
| product_id | name | stock | description |
|---|---|---|---|
| 1 | Desk Lamp | 12 | 'Brass, 40cm tall' |
| 2 | Notebook | 0 | 'A5, 80 pages' |
| 3 | Mug | NULL | '' |
| 4 | Backpack | 7 | NULL |
- Notebook, stock 0: someone counted the shelf and found none. Sold out is a fact you can act on.
- Mug, stock NULL: no count was recorded. The shelf could hold 0 mugs or 500.
- Mug, description '': the seller saved the form with the box blank. An answer exists, and it is zero characters long.
- Backpack, description NULL: no description was ever saved for this product.
Why the difference changes answers
Where NULLs come from
- An optional field was skipped: a customer checked out without entering a phone number.
- The value does not exist yet: an order placed today has no delivery date.
- The question does not apply: a house has no apartment number.
- The column is newer than the row: a loyalty_tier column added this year is NULL for every customer who signed up before it existed.
| In the cell | A value? | Reads as |
|---|---|---|
| 0 | Yes, a number | Measured, and the amount is zero |
| '' | Yes, text | Saved, with no characters in it |
| NULL | No | Nothing was recorded |
description = '' and see whether the row comes back.Deciding what to store is a modelling choice that someone makes for every column. Try it on a tip column in a food delivery app's orders table.
An orders table has a tip column. For which order is NULL the accurate thing to store?
A comparison such as amount > 150 has had 2 possible results so far: TRUE or FALSE. NULL adds a third. Ask whether an unrecorded region equals 'US' and the truthful reply is "can't tell". SQL calls that result UNKNOWN, and a query shows it as NULL.
Seeing the third value
ORD-001 and ORD-005 come back TRUE and ORD-003 comes back FALSE. ORD-002 and ORD-004 have no region recorded, so the comparison has nothing on its left side to check, and is_us is NULL for both. Guessing FALSE would be a claim about a region nobody recorded, so the engine reports that it cannot tell.
- ▸TRUE: the row is kept.
- ▸FALSE: the row is dropped.
- ▸UNKNOWN: the row is dropped, exactly as if it were FALSE.
Opposite filters that lose rows
In a table with no NULLs, the filter region = 'US' and its opposite region != 'US' split the rows into 2 piles that add up to the whole. NULLs add a third pile that neither filter returns. Here is each comparison worked out row by row.
| order_id | region | region = 'US' | region != 'US' |
|---|---|---|---|
| ORD-001 | US | TRUE | FALSE |
| ORD-002 | NULL | UNKNOWN | UNKNOWN |
| ORD-003 | EU | FALSE | TRUE |
| ORD-004 | NULL | UNKNOWN | UNKNOWN |
| ORD-005 | US | TRUE | FALSE |
Even NULL = NULL is unknown
The natural next move is to ask for the missing regions directly with region = NULL. Play the query and watch what each row's comparison produces.
SELECT*FROM ordersWHERE region = NULL
Every comparison operator you know behaves this way. Test a NULL with < or > and you get UNKNOWN. != and IN give the same answer.
AND with an unknown side
| Left side | Right side | Left AND right | Row kept? |
|---|---|---|---|
| TRUE | TRUE | TRUE | Yes |
| TRUE | UNKNOWN | UNKNOWN | No |
| FALSE | UNKNOWN | FALSE | No |
| UNKNOWN | UNKNOWN | UNKNOWN | No |
Take WHERE region = 'US' AND amount > 250 on ORD-004, which has amount 300 and no region. The amount test is TRUE and the region test is UNKNOWN, so the row lands on the second line of the table and is dropped, even though its amount passes.
orders holds 5 rows of (order_id, amount, region): (ORD-001, 100, US), (ORD-002, 200, NULL), (ORD-003, 150, EU), (ORD-004, 300, NULL), (ORD-005, 250, US). Which orders does this query return?
SQL has a dedicated test for a missing value. phone IS NULL asks one thing about a cell: was anything recorded here? Unlike a comparison, that question always has a definite answer, so IS NULL returns TRUE or FALSE and never UNKNOWN.
The keyword is IS, because = compares 2 values and a NULL cell has no value to compare.
A shop's customers table has 4 people in it, and the support team wants to know who can't be reached by phone. Play the query to see the test run on each row.
SELECTcustomer_id,name,phoneFROM customersWHERE phone IS NULL
Ben and Dev come back. For Ann and Cara the test is FALSE, because a phone number is sitting in the cell. For Ben and Dev it is TRUE. Every row got a yes or a no, which is exactly what the = comparison couldn't deliver.
The opposite test
IS NOT NULL flips the answer: TRUE when the cell holds a value, FALSE when it does not. It's the filter for "only rows where this was recorded", such as the customers a courier can call.
It returns Ann and Cara. 2 rows from IS NULL plus 2 rows from ISN'T NULL make all 4 customers. This pair always splits a table with nothing left over, because each row answers TRUE to exactly one of them. Compare that with = 'US' and != 'US' in the last section, which lost 2 of 5 orders between them.
3 tests on the same 3 cells
The table below runs 3 tests on 3 possible contents of a phone cell. The middle row is the one from the first section: an empty string is a value, so IS NULL doesn't catch it.
| phone holds | phone = NULL | phone IS NULL | phone IS NOT NULL |
|---|---|---|---|
| '555-0101' | UNKNOWN | FALSE | TRUE |
| '' | UNKNOWN | FALSE | TRUE |
| NULL | UNKNOWN | TRUE | FALSE |
Combining it with other conditions
Auditing a column before you trust it
IS NULL is most useful as a check you run before any analysis, to find out how much of a column is missing. Pair the test with COUNT(*) and the size of the gap comes back as one number.
The same pair of tools settles the puzzle from the last section. To report every order that isn't confirmed as US, you need 2 filters. region != 'US' finds 1 order with a different region and region IS NULL finds the 2 with no region at all, so the answer is 3. Together with the 2 US orders, all 5 rows are accounted for.
- Write IS NULL to find rows where a value is missing.
- Write ISN'T NULL to keep only rows where a value was recorded.
- Count the NULLs in a column before filtering or grouping on it.
- Write = NULL or != NULL. Both return 0 rows and raise no error.
- Expect IS NULL to catch empty strings. '' is a value.
- Assume a filter and its opposite cover every row of the table.
> The warehouse team wants the order_id and amount of every order above 150 that has a region recorded. Arrange the tiles into that query. 2 tiles do not belong.
You've used both COUNT(*) and COUNT(column). On a column with no gaps they return the same number, which hides the fact that they ask different questions. COUNT(*) counts rows. COUNT(column) counts the rows where that column holds a value, and it steps over every NULL.
Here are the shop's 5 orders again, this time with their discount column: the amount taken off by a coupon. 3 orders have a discount recorded and 2 have NULL. Play the query to watch both counts walk the same rows.
SELECTCOUNT(*) AS total_rows,COUNT(discount) AS rows_with_discountFROM orders
total_rows is 5 and rows_with_discount is 3. Read the star in COUNT(*) as "the row itself". A row exists whether or not its cells are filled, so a row full of NULLs still counts as 1 and no NULL can ever make COUNT(*) smaller. COUNT(discount) looks at one cell per row and adds 1 only when that cell has something in it.
Which count answers which question
| Question | Count to use | Answer here |
|---|---|---|
| How many orders were placed? | COUNT(*) | 5 |
| How many orders have a discount recorded? | COUNT(discount) | 3 |
| How many orders have no discount recorded? | COUNT(*) - COUNT(discount) | 2 |
The same rule inside every group
GROUP BY changes nothing about the rule. Each group gets its own COUNT(*) and its own COUNT(discount), and the second one skips the NULLs inside that group. The orders also carry a channel column saying whether they came from the web or the app.
2 details that follow from the rule
- COUNT(DISTINCT column) skips NULLs as well. A region column holding US, NULL, EU, NULL, US has 2 distinct values to count, so the answer is 2.
- COUNT never returns NULL. When every cell in the column is NULL, COUNT(column) returns 0, and that 0 is a real measurement: zero rows had a value.
How this goes wrong at work
The classic mistake is writing COUNT(some_column) out of habit when the question was about rows. The query runs, the number looks plausible, and it's too low by exactly the number of NULLs in that column. A table of 2,000,000 signups with a 3% NULL rate in referral_code would be reported as 1,940,000 signups.
The reverse mistake happens too: using COUNT(*) to answer "how many customers gave us a phone number?" and counting the customers who gave none. Before typing either one, say the question aloud. If it is about rows, use the star. If it's about a recorded value, name the column.
COUNT(order_id) equals COUNT(*) only while order_id has no NULLs. When you mean rows, write COUNT(*): it says so, and it stays correct if the column gains a gap later.customers has 4 rows, and phone is NULL in 2 of them. What does this query return?
SUM and AVG treat a NULL the way COUNT(column) does, and so do MIN and MAX: they read the cells that hold a value and pass over the rest. Nothing warns you and no 0 goes in its place, so the aggregate runs as if the rows with NULL were absent from the table.
SELECTSUM(discount) AS total_discount,AVG(discount) AS avg_discountFROM orders
2 averages, 2 different questions
- Divides by 3, the orders with a discount recorded
- Answers: when a discount is recorded, how big is it?
- Says nothing about the 2 orders with NULL
- Divides by 5, every order in the table
- Answers: how much discount does the shop give per order?
- Treats each NULL as a discount of 0
MIN and MAX
When every value is missing
rows_kept is 2 and discounts_found is 0, but discount_total is NULL. SUM had no values to add, so it reports that it has no total, which is different from a total of 0. AVG returns NULL here for the same reason, as do MIN and MAX. COUNT is the one aggregate that answers with a number when nothing is there.
| Aggregate | On 10, NULL, 15, NULL, 25 | On NULL, NULL |
|---|---|---|
| COUNT(*) | 5 | 2 |
| COUNT(discount) | 3 | 0 |
| SUM(discount) | 50 | NULL |
| AVG(discount) | 16.67 | NULL |
| MIN(discount) | 10 | NULL |
| MAX(discount) | 25 | NULL |
Shipping a number people can trust
An aggregate over a column with gaps is a statement about part of the table, and whoever reads your number needs to know how big that part is. Put COUNT(*) and COUNT(column) next to every SUM or AVG you report.
- Report COUNT(*) and COUNT(column) beside every SUM or AVG.
- Find out what NULL means in a column before averaging it.
- Use SUM(column) * 1.0 / COUNT(*) when NULL should count as 0; the 1.0 keeps the fraction.
- Assume AVG divides by the number of rows in the table.
- Expect SUM to return 0 when every value is NULL. It returns NULL.
- Treat MIN as the smallest value across all rows when some are NULL.
A reviews table has 4 rows. Read from top to bottom, its rating column holds 5, NULL, 3, NULL. What does this query return?
> Back to the new listing in Lisbon. Suppose a listings table holds 1,000 listings for the city, and 150 of them are too new to have a rating, so rating is NULL in those rows. A product manager asks 3 questions: how many listings are there, what is the average rating, and how many listings are rated below 4.5?
COUNT(*) returns 1,000 and COUNT(rating) returns 850. The 150 between them are the new listings, the same rows that WHERE rating IS NULL returns.AVG(rating) averages the 850 rated listings. Had the gaps been stored as 0, the same average would be divided by 1,000 and come out 15% lower.WHERE rating < 4.5 returns rated listings only. For a new listing the comparison is UNKNOWN, so it is missing from that result and from rating > 4.5 as well.= 0 and = '' never match a NULL.IS NULL and IS NOT NULL always return TRUE or FALSE, so together they cover every row of a table.COUNT(*) counts rows and COUNT(column) counts recorded values. Their difference is the number of NULLs in the column.NULL means a value is missing, and every comparison, count and average treats that gap by its own rule.
NULL: the billion dollar mistake
- Category
- SQL
- Difficulty
- beginner
- Duration
- 25 minutes
- Challenges
- 12 hands-on challenges
Topics covered: NULL vs zero vs empty string, Three-Valued Logic, IS NULL and IS NOT NULL operators, COUNT(*) vs COUNT(column), Aggregates with NULLs
Lesson Sections
- NULL vs zero vs empty string
Every cell in a table holds one of 2 things: a value, or a marker saying that no value was recorded. That marker is NULL. It is how a database writes "we don't know" or "this doesn't apply" inside a cell. Zero and the empty string both look like nothing, yet both are values. 0 is a number that someone measured or typed. '' is a piece of text that happens to contain no characters. NULL marks the absence of any value, which is why a column of any type can hold it: an INTEGER column can, and so can
- Three-Valued Logic (concepts: Three-Valued Logic)
Logic with 3 possible results is called three-valued logic. It follows one idea all the way through: when an input is missing, the result is whatever can still be known for certain, and often that is nothing. Seeing the third value A comparison is an expression, so it can sit in a SELECT list where its result shows up as a column. This query asks every order whether its region is 'US'. That third line is where NULL changes results. WHERE only lets a row through when its condition is TRUE, so a r
- IS NULL and IS NOT NULL operators (concepts: Null Handling)
The keyword is IS, because = compares 2 values and a NULL cell has no value to compare. The opposite test 3 tests on the same 3 cells Combining it with other conditions IS NULL is a condition like any other, so AND can join it to the comparisons you already write. And because it never returns UNKNOWN, it adds no third value to the AND. The finance team wants large orders that still need a region filled in. Only ORD-004 qualifies. ORD-002 also has no region, but its amount of 200 fails the second
- COUNT(*) vs COUNT(column) (concepts: Counting)
Which count answers which question Subtracting one count from the other, as the third row does, gives the number of NULLs in a column without writing a WHERE, so it can sit beside other aggregates in the same query. The same rule inside every group The web channel has 3 orders and 2 of them carry a discount. The app channel has 2 orders and 1 with a discount. Anyone reading only the discount column would conclude the shop took 3 orders in total, when it took 5. The gap between the 2 columns is t
- Aggregates with NULLs (concepts: Sums & Averages)
Discounts on the 5 orders run 10, NULL, 15, NULL, 25. Before playing the query, work out what you expect the total and the average to be. The total is 50: 10 plus 15 plus 25. That number is the same whether you picture the NULLs as skipped or as zeros. The average is where the 2 pictures split. AVG divides 50 by 3, the number of recorded discounts, and returns around 16.67. Dividing by all 5 orders would give 10. 2 averages, 2 different questions Both numbers are correct arithmetic. Which one be