Sub topic 5
How DISTINCT treats NULL values
This chapter covers how DISTINCT and COUNT(DISTINCT ...) handle NULL. It assumes you can write a basic SELECT ... FROM, filter with WHERE, sort with ORDER BY, and that you know what tables, rows, and columns are. You should also have seen SELECT DISTINCT on one and several columns, and COUNT(DISTINCT column), from earlier chapters.
The apparent contradiction
In SQL, NULL means "unknown" or "no value". Comparing anything to NULL with = gives neither true nor false. It gives UNKNOWN:
SELECT NULL = NULL AS same;This returns NULL, not TRUE. So two NULL values are not "equal" under the normal comparison rules. A WHERE clause that tests x = NULL never matches a row.
DISTINCT still has to decide which rows are duplicates. If it used =, every NULL would be different from every other NULL, and a column with 1,000 NULLs would produce 1,000 NULL rows. That is not what happens.
The rule: NULLs are treated as the same value for DISTINCT
For the purpose of removing duplicates, the SQL standard says two NULLs are not distinct from each other. DISTINCT therefore keeps exactly one NULL row, the same way it keeps one row for any repeated value.
The standard calls this idea "is not distinct from". Two values are not distinct if they are equal, or if both are NULL. GROUP BY and UNION use the same rule.
Here is a small table to try it on:
CREATE TABLE customers_demo (
customer_id INTEGER PRIMARY KEY,
country VARCHAR(30),
city VARCHAR(30)
);
INSERT INTO customers_demo (customer_id, country, city) VALUES
(1, 'Germany', 'Berlin'),
(2, 'Germany', 'Munich'),
(3, 'France', 'Paris'),
(4, NULL, 'Lisbon'),
(5, NULL, 'Madrid'),
(6, 'France', NULL),
(7, NULL, NULL),
(8, NULL, NULL);Now select the distinct countries:
SELECT DISTINCT country
FROM customers_demo;The result has three rows: Germany, France, and one NULL. Four rows had a NULL country, but they collapse into a single row.
Multiple columns: NULL pairs also match
With several columns, DISTINCT compares the whole row. A NULL in a column matches a NULL in the same column of another row. Other columns still have to match too.
SELECT DISTINCT country, city
FROM customers_demo
ORDER BY country, city;The result has these rows, in some order (the placement of NULL in sorting depends on the database, covered below):
| country | city |
|---|---|
| France | Paris |
| France | NULL |
| Germany | Berlin |
| Germany | Munich |
| NULL | Lisbon |
| NULL | Madrid |
| NULL | NULL |
Rows 7 and 8 are both (NULL, NULL), so they collapse into one row. Rows 4 and 5 both have a NULL country but different cities, so they stay separate.
COUNT(DISTINCT) ignores NULL
COUNT(DISTINCT column) behaves differently from SELECT DISTINCT column. Aggregate functions, except COUNT(*), skip NULL inputs. COUNT(DISTINCT country) first discards NULLs, then counts the different remaining values.
SELECT COUNT(DISTINCT country) AS country_count
FROM customers_demo;This returns 2 (Germany and France). The NULL group is not counted.
Compare it with the number of rows that SELECT DISTINCT country returns, which is 3. The two numbers differ by one whenever the column contains at least one NULL.
| Expression | Result on the demo table | Treats NULL as |
|---|---|---|
| `SELECT DISTINCT country` | 3 rows | One value, kept |
| `COUNT(DISTINCT country)` | 2 | Missing, skipped |
| `COUNT(*)` | 8 | A row like any other |
| `COUNT(country)` | 4 | Missing, skipped |
Counting the NULL group too
If you want the count to include the NULL group, you have a few options. The simplest is to add one when a NULL exists:
SELECT COUNT(DISTINCT country)
+ CASE WHEN COUNT(*) > COUNT(country) THEN 1 ELSE 0 END AS country_count_with_null
FROM customers_demo;COUNT(*) counts all rows and COUNT(country) counts only non-NULL rows. If the first is larger, at least one NULL exists. This returns 3.
Another option is to replace NULL with a placeholder before counting:
SELECT COUNT(DISTINCT COALESCE(country, 'unknown')) AS country_count_with_null
FROM customers_demo;This also returns 3. Be careful with this approach. If a real row contains the text 'unknown', it merges with the NULL rows and the count is too low. Pick a placeholder that cannot occur in the data, or use the CASE form.
Multi-column COUNT(DISTINCT) is not portable
You may be tempted to write COUNT(DISTINCT country, city). MySQL accepts it, and it skips any row where at least one of the columns is NULL. PostgreSQL, SQL Server, and SQLite do not accept it. A portable way to count distinct pairs is to count the rows of a DISTINCT subquery:
SELECT COUNT(*) AS pair_count
FROM (
SELECT DISTINCT country, city
FROM customers_demo
) AS pairs;This returns 7, because the subquery keeps the NULL pairs and COUNT(*) counts every row.
Where NULL sorts
When you pair DISTINCT with ORDER BY, the NULL row has to go somewhere. The SQL standard leaves the position to the database, and the products differ:
| Database | NULL position in ascending order (default) |
|---|---|
| PostgreSQL | Last |
| Oracle | Last |
| MySQL | First |
| SQLite | First |
| SQL Server | First |
PostgreSQL, Oracle, and SQLite (3.30+) accept NULLS FIRST and NULLS LAST to override the default. MySQL and SQL Server do not, so you sort on an expression instead:
SELECT DISTINCT country
FROM customers_demo
ORDER BY CASE WHEN country IS NULL THEN 1 ELSE 0 END, country;The CASE expression is 0 for real countries and 1 for NULL, so NULL goes last in every database.
Filtering NULL out
If you do not want a NULL row in the result, filter it before DISTINCT runs:
SELECT DISTINCT country
FROM customers_demo
WHERE country IS NOT NULL;Use IS NULL and IS NOT NULL. Writing WHERE country <> NULL or WHERE country = NULL returns no rows, because the comparison yields UNKNOWN.
A related trap is NOT IN with a subquery that can return NULL. x NOT IN (SELECT DISTINCT country ...) returns no rows at all if the subquery contains a NULL. Adding WHERE country IS NOT NULL inside the subquery avoids it. The DISTINCT does not help here, because it keeps one NULL.
Common errors
- Expecting one row per NULL.
DISTINCTreturns oneNULLrow, not one per source row. If you need to know how many rows hadNULL, useCOUNT(*) - COUNT(country)orCOUNT(*) FILTER (WHERE country IS NULL)(PostgreSQL and SQLite). - Using
COUNT(DISTINCT col)as the number of rowsDISTINCT colreturns. They disagree by one whenNULLis present. - Merging
NULLwith a placeholder by accident.COALESCE(country, '')makesNULLand an empty string identical. In Oracle, an empty string is alreadyNULL, so the two are the same there even withoutCOALESCE. - Assuming
NULLsorts the same everywhere. See the table above. - Comparing with
=instead ofIS NOT DISTINCT FROM. PostgreSQL and SQLite offerIS NOT DISTINCT FROM(MySQL spells it<=>) for aNULL-safe equality test. It follows the same rule thatDISTINCTuses internally.
SELECT a.customer_id, b.customer_id AS other_id
FROM customers_demo AS a
JOIN customers_demo AS b
ON a.country IS NOT DISTINCT FROM b.country
AND a.customer_id < b.customer_id
ORDER BY a.customer_id, b.customer_id;This pairs customers with the same country, including customers whose country is NULL. A plain a.country = b.country would never pair two NULL rows.
Summary of the rules
SELECT DISTINCTtreats allNULLs in a column as equal and returns a singleNULLrow.- With several columns, a
NULLmatches aNULLin the same column, and the whole row must match. COUNT(DISTINCT col)ignoresNULL, so it can be one lower than the number of rowsSELECT DISTINCT colreturns.- Where
NULLsorts is database-specific. State it explicitly when order matters. - Use
IS NULLandIS NOT NULL, never= NULL.
Exercise
A table employees has a nullable column manager_id. It has 10 rows. Six have manager_id values 1, 1, 2, 2, 2, 3, and four have NULL. What do SELECT DISTINCT manager_id, COUNT(DISTINCT manager_id), and COUNT(manager_id) return?
Show answer
SELECT DISTINCT manager_id returns 4 rows: 1, 2, 3, and one NULL row. COUNT(DISTINCT manager_id) returns 3, because NULL is skipped and the distinct non-NULL values are 1, 2, and 3. COUNT(manager_id) returns 6, the number of non-NULL values, because it counts duplicates but skips NULL.
Exercise
Write a query that returns the number of distinct countries in customers_demo, counting NULL as its own group, without using a placeholder value.
Show answer
SELECT COUNT(*) FROM (SELECT DISTINCT country FROM customers_demo) AS c; counts the rows of the DISTINCT result, which includes the single NULL row, so it returns 3. The CASE form shown earlier also works.