Sub topic 11
NULL in GROUP BY, DISTINCT, and UNION
This chapter assumes you know basic SELECT, WHERE, GROUP BY, and UNION queries. The key idea is that SQL treats NULL as missing or unknown in expressions, but grouping and duplicate removal need a practical rule: rows with NULL in the same position are treated as belonging together.
Grouping NULL values
GROUP BY places rows with the same grouping value in one group. All NULL values form one group, even though NULL = NULL does not evaluate to TRUE.
Using the sample employees table:
SELECT commission, COUNT(*) AS employee_count
FROM employees
GROUP BY commission;The result contains one group for the two missing commissions:
| commission | employee_count |
|---|---|
| NULL | 2 |
| 100.00 | 1 |
| 300.00 | 1 |
The NULL group means “rows where commission is missing.” It does not mean that the missing commissions have been proven equal.
You can label that group with COALESCE:
SELECT COALESCE(CAST(commission AS VARCHAR(20)), 'not recorded') AS commission_label,
COUNT(*) AS employee_count
FROM employees
GROUP BY commission;Group by the original column, not only the displayed label, when different stored values could become the same label. For example, replacing both NULL and a real text value such as 'not recorded' with the same label could combine distinct categories.
DISTINCT removes duplicate NULLs
DISTINCT removes duplicate result rows. For duplicate detection, SQL treats NULL values in corresponding columns as matching.
SELECT DISTINCT manager_id
FROM employees;This returns one row for each manager ID, plus one row for NULL:
| manager_id |
|---|
| NULL |
| 1 |
| 2 |
If you need to count employees with a missing manager separately, test for NULL explicitly:
SELECT
COUNT(*) AS all_employees,
COUNT(DISTINCT manager_id) AS distinct_non_null_managers,
COUNT(*) - COUNT(manager_id) AS employees_without_manager
FROM employees;COUNT(DISTINCT manager_id) ignores NULL, so it does not count the missing-manager group.
UNION and UNION ALL
UNION combines compatible queries and removes duplicate rows. UNION ALL combines them without removing duplicates.
SELECT manager_id
FROM employees
WHERE id IN (1, 2, 3)
UNION
SELECT manager_id
FROM employees
WHERE id IN (1, 3, 4);The first query produces NULL, 1, 1. The second produces NULL, 1, 2. UNION returns only NULL, 1, 2.
SELECT manager_id
FROM employees
WHERE id IN (1, 2, 3)
UNION ALL
SELECT manager_id
FROM employees
WHERE id IN (1, 3, 4);UNION ALL keeps every row, including both NULL rows and all repeated 1 values. Use it when duplicates represent separate events or when you know the inputs cannot overlap. Use UNION when duplicate removal is part of the result's meaning.
Exercise
Exercise
A table contains values 10, NULL, NULL, and 20. How many rows does SELECT DISTINCT value return, and how many groups does GROUP BY value create?
Show answer
Each creates three results: one for 10, one for 20, and one group or result row for all the NULL values.