DISTINCT and NULL

Concepts covered: Deduplication

SELECT DISTINCT keeps one row for each different combination of values, and it judges sameness the way UNION does when it removes duplicates. In employee_metrics, 2 of the 6 employees have no department recorded. Play the query and count the NULL rows that come out.

SELECT DISTINCT department
FROM employee_metrics
employee_metrics
namedepartment
AnnSales
BenNULL
CaraEng
DevSales
EveNULL
FinnEng

The query returns 3 rows: Sales, Eng and a single NULL, which stands for both Ben and Eve. Now count the departments with COUNT(DISTINCT department) and the answer is 2. Aggregates discard NULL inputs before doing anything else, and the DISTINCT inside COUNT follows the same order, so the NULL value that SELECT DISTINCT kept never reaches the count.

SELECT
  COUNT(*) AS all_rows,
  COUNT(department) AS known_department,
  COUNT(DISTINCT department) AS distinct_departments,
  (
    SELECT
      COUNT(*)
    FROM (
      SELECT DISTINCT
        department
      FROM employee_metrics
    ) AS d
  ) AS distinct_rows
FROM employee_metrics
employee_metrics
namedepartment
AnnSales
BenNULL
CaraEng
DevSales
EveNULL
FinnEng
Result
all_rowsknown_departmentdistinct_departmentsdistinct_rows
6423

The 4 numbers answer 4 different questions. A pipeline check that compares distinct_rows from one step with distinct_departments from another reports a mismatch of 1 whenever the column holds a NULL, though no row is wrong. Decide which question the check asks, then use the matching count on both sides. GROUP BY department follows the SELECT DISTINCT rule and returns a single group for Ben and Eve, with a NULL key and a count of 2.

With more than one column, DISTINCT compares whole rows. ('Sales', NULL) and ('Sales', NULL) are duplicates, while ('Sales', NULL) and ('Sales', 'Berlin') are kept apart, because a NULL differs from every known value.

Defaults that merge groups

Replacing NULL with a label before deduplicating, as in COALESCE(department, 'Unknown'), makes the NULL group readable and lets COUNT(DISTINCT) include it. It also merges the NULL rows with any real value equal to the label. A source that already writes 'Unknown', or an empty string when the default is '', collapses into the same group, and the distinct count drops by 1 with no warning. Pick a label the data can't contain, or check for it first.

staff has 4 rows whose departments are 'Sales', 'Unknown', NULL and NULL. What does this query return?

SELECT
  COUNT(DISTINCT COALESCE(department, 'Unknown')) AS departments
FROM staff

Comparing values that may be NULL

SQL exposes the deduplication rule as an operator you can put in your own conditions. a IS DISTINCT FROM b is TRUE when the values differ, and it treats NULL as an ordinary value: a NULL against a known value is distinct, and a NULL against a NULL is not. It always returns TRUE or FALSE. IS NOT DISTINCT FROM is its negation.

aba <> ba IS DISTINCT FROM b
11FALSEFALSE
12TRUETRUE
1NULLNULLTRUE
NULLNULLNULLFALSE

The difference matters most in change detection. tier_changes holds each customer's loyalty tier from yesterday's snapshot and from today's. Compare the 2 filters.

tier_changes
customer_idold_tiernew_tier
1GoldGold
2SilverGold
3NULLGold
4GoldNULL
5NULLNULL

Using <>

Keeps only rows where both tiers are known and different.

SELECT
  customer_id,
  old_tier,
  new_tier
FROM tier_changes
WHERE old_tier <> new_tier
ORDER BY customer_id
Result
customer_idold_tiernew_tier
2SilverGold

IS DISTINCT

Also keeps customers who gained a tier from NULL or lost theirs to NULL.

SELECT
  customer_id,
  old_tier,
  new_tier
FROM tier_changes
WHERE old_tier IS DISTINCT FROM new_tier
ORDER BY customer_id
Result
customer_idold_tiernew_tier
2SilverGold
3NULLGold
4GoldNULL

With <>, customer 3's first tier and customer 4's lost tier both evaluate to NULL and drop out, so a change feed built on it never reports a customer joining or leaving the program. IS DISTINCT FROM returns customers 2, 3 and 4 and still skips customer 5, whose tier was unknown on both days.

About this lesson

This section is part of the NULL Values: Advanced lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.