Sub topic 11
NULL in GROUP BY, DISTINCT, and UNION
This chapter assumes you know how NULL behaves in comparisons and WHERE (earlier chapters), plus basic GROUP BY and aggregates. The examples use the employees table from the start of this tutorial: Ada (no manager, no commission), Ben (manager 1, commission 100), Cy (manager 1, no commission), Di (manager 2, commission 300).
The apparent contradiction
In WHERE, NULL = NULL is UNKNOWN, so two NULLs never match. Yet GROUP BY puts all NULLs into one group, and DISTINCT collapses them into one row. This is not an inconsistency. SQL uses two different notions of sameness:
- Equality (
=) answers "are these two values equal?" and returns UNKNOWN when either side is NULL. - Not distinct answers "do these two values count as duplicates?" Two NULLs are not distinct from each other, and a NULL is distinct from any non-NULL value.
GROUP BY, DISTINCT, UNION, INTERSECT, and EXCEPT all use the second notion. It is the same rule that IS DISTINCT FROM exposes in expressions. The SQL standard words it as "two NULLs are not distinct". It does not say the NULLs are equal.
NULL in GROUP BY
GROUP BY creates exactly one group for all rows whose grouping column is NULL. That group is a normal group and gets its own output row.
SELECT manager_id,
COUNT(*) AS employees,
COUNT(commission) AS with_commission,
SUM(commission) AS total_commission
FROM employees
GROUP BY manager_id;The result has three rows, in no guaranteed order:
| manager_id | employees | with_commission | total_commission |
|---|---|---|---|
| NULL | 1 | 0 | NULL |
| 1 | 2 | 1 | 100.00 |
| 2 | 1 | 1 | 300.00 |
Two details matter here:
- The NULL row in
manager_idis the group of employees with no manager. It is not an error or a leftover. SUMover a group where every value is NULL returns NULL, not 0, whileCOUNT(commission)returns 0. Wrap the sum inCOALESCE(SUM(commission), 0)if you need a number.
Multiple grouping columns
With several columns, two rows fall into the same group when every column is not distinct, column by column. A NULL in one column does not split a group or merge it with another.
SELECT manager_id, commission, COUNT(*) AS n
FROM employees
GROUP BY manager_id, commission;This returns four groups: (NULL, NULL), (1, 100.00), (1, NULL), and (2, 300.00). Ben and Cy share manager_id = 1 but land in different groups because their commissions differ (100 versus NULL).
Telling a real NULL group from a label
A NULL in the output is ambiguous when you also use ROLLUP, CUBE, or GROUPING SETS, because those features produce NULL in a grouping column to mean "all values". The GROUPING() function tells the two cases apart. It returns 1 when the column was rolled up and 0 when it is an ordinary value.
SELECT manager_id,
COUNT(*) AS employees,
GROUPING(manager_id) AS is_total
FROM employees
GROUP BY ROLLUP (manager_id);You get four rows. The row (NULL, 1, 0) is the group of employees with no manager. The row (NULL, 4, 1) is the grand total. Without GROUPING(), both look like manager_id = NULL. This syntax works in PostgreSQL, SQL Server, and Oracle. MySQL spells it GROUP BY manager_id WITH ROLLUP.
Replacing NULL for display
You can label the NULL group by combining COALESCE with a cast, as long as you accept that the label could collide with a real value.
SELECT COALESCE(CAST(manager_id AS VARCHAR(10)), 'none') AS manager,
COUNT(*) AS employees
FROM employees
GROUP BY COALESCE(CAST(manager_id AS VARCHAR(10)), 'none');The cast is needed because COALESCE requires compatible types. The expression is repeated in GROUP BY for portability. Some systems allow grouping by the output alias, but not all do. If a real manager_id could ever render as 'none', the two groups would merge silently. For integer keys that cannot happen.
NULL in DISTINCT
SELECT DISTINCT removes duplicate rows, and NULLs count as duplicates of each other.
SELECT DISTINCT commission FROM employees;This returns three rows: NULL, 100.00, and 300.00. Ada and Cy both have a NULL commission, and they collapse into one row.
For several columns, the whole row is compared. SELECT DISTINCT manager_id, commission returns four rows, matching the four groups above.
COUNT(DISTINCT ...) is different
COUNT(DISTINCT column) is an aggregate, so it skips NULLs before it removes duplicates. This produces a count that disagrees with the number of rows SELECT DISTINCT returns.
SELECT COUNT(DISTINCT commission) AS distinct_non_null -- 2
FROM employees;SELECT DISTINCT commission returns 3 rows, and COUNT(DISTINCT commission) returns 2. If you want NULL counted as one more value, add it explicitly:
SELECT COUNT(DISTINCT commission)
+ MAX(CASE WHEN commission IS NULL THEN 1 ELSE 0 END) AS distinct_incl_null
FROM employees;This returns 3.
NULL in UNION, INTERSECT, and EXCEPT
The set operators compare whole rows using the not-distinct rule, just like DISTINCT.
UNIONremoves duplicates, so two NULL rows become one.UNION ALLdoes no comparison and keeps every row, so both NULLs survive.INTERSECTreturns rows that appear on both sides, and a NULL row on each side matches.EXCEPTremoves rows that appear on the right, and a NULL row on the right removes a NULL row on the left.
SELECT commission FROM employees WHERE id = 1 -- NULL
UNION
SELECT commission FROM employees WHERE id = 3; -- NULL
-- One row: NULL
SELECT commission FROM employees WHERE id = 1
UNION ALL
SELECT commission FROM employees WHERE id = 3;
-- Two rows: NULL, NULLEXCEPT as a NULL-safe NOT IN
Recall the NOT IN trap: id NOT IN (SELECT manager_id ...) returns nothing when the subquery contains a NULL. EXCEPT does not have that problem, because it compares with the not-distinct rule. It also shows the NULL as a surviving value:
SELECT manager_id FROM employees
EXCEPT
SELECT id FROM employees;The left side is {NULL, 1, 2} after duplicate removal, and the right side is {1, 2, 3, 4}. The result is one row: NULL. No row is wrongly lost.
Because EXCEPT removes duplicates and works on whole rows, it answers a different question than NOT EXISTS. Use it when you want a set difference of values, and use NOT EXISTS when you want the full rows of one table.
Summary of behavior
| Feature | Two NULLs treated as | Example result |
|---|---|---|
| `WHERE a = b` | UNKNOWN (no match) | Row filtered out |
| `JOIN ... ON a = b` | UNKNOWN (no match) | Rows do not join |
| `GROUP BY` | Same group | One NULL group |
| `DISTINCT` | Duplicates | One NULL row |
| `UNION`, `INTERSECT`, `EXCEPT` | Duplicates | One NULL row, and NULLs match across sides |
| `UNION ALL` | Not compared | Both rows kept |
| `COUNT(DISTINCT col)` | Skipped | NULLs not counted |
Gotchas and portability
- Window functions.
PARTITION BYfollows the same rule asGROUP BY, so all NULL keys form one partition. - Oracle and empty strings. Oracle stores an empty string as NULL, so
''and NULL group together there. In other systems they form separate groups. - Set operator support.
INTERSECTandEXCEPTexist in PostgreSQL, SQL Server, and SQLite. MySQL added them in 8.0.31. Oracle usesMINUSin older versions andEXCEPTfrom 21c. - Column types. Set operators need compatible column types. A bare
SELECT NULLon one side can fail type resolution in some systems, so cast it, for exampleCAST(NULL AS NUMERIC(8,2)). - Result order. None of these features guarantees where the NULL row appears. Add
ORDER BY ... NULLS FIRSTorNULLS LASTwhen order matters.
Exercise
Using the employees table, what do these three queries return, in terms of row counts? (1) SELECT DISTINCT commission FROM employees; (2) SELECT COUNT(DISTINCT commission) FROM employees; (3) SELECT commission FROM employees UNION ALL SELECT commission FROM employees; Explain the difference between (1) and (2).
Show answer
Query (1) returns 3 rows (NULL, 100.00, 300.00), because DISTINCT treats the two NULLs as duplicates and keeps one NULL row. Query (2) returns 2, because COUNT(DISTINCT ...) is an aggregate and skips NULLs before counting. Query (3) returns 8 rows, because UNION ALL keeps every row from both sides without comparing them.
Exercise
Write a query that returns the number of employees for each manager_id, with the employees who have no manager shown as their own row, and add a grand total row. How can you tell the "no manager" row from the grand total row?
Show answer
SELECT managerid, COUNT(*) AS employees, GROUPING(managerid) AS istotal FROM employees GROUP BY ROLLUP (managerid); Both rows show NULL in managerid, but the "no manager" row has istotal = 0 and a count of 1, and the grand total row has is_total = 1 and a count of 4.