Sub topic 4
Counting unique values with COUNT(DISTINCT)
This chapter assumes you can write a basic SELECT ... FROM ... WHERE query, sort with ORDER BY, and group rows with GROUP BY. It also assumes you have met SELECT DISTINCT in the previous chapters. The examples use a customers table with customer_id, country, and city columns, and an orders table with order_id, customer_id, order_date, and total columns.
Rows versus unique values
SELECT DISTINCT country FROM customers returns a list of countries. Often you do not want the list. You want to know how many different countries there are. COUNT(DISTINCT column) answers that question in one value.
SELECT COUNT(DISTINCT country) AS country_count
FROM customers;This query returns a single row with a single column. If the table holds 5,000 customers spread over 42 countries, country_count is 42, not 5,000.
Compare it with the other forms of COUNT:
| Expression | What it counts |
|---|---|
| `COUNT(*)` | Every row in the group, including rows with NULLs |
| `COUNT(country)` | Rows where `country` is not NULL, duplicates included |
| `COUNT(DISTINCT country)` | Different non-NULL values of `country` |
Each form is correct for a different question. COUNT(*) answers "how many customers do we have?". COUNT(DISTINCT country) answers "in how many countries do we have customers?".
How it works internally
COUNT(DISTINCT x) is an aggregate function. For each group (or for the whole table, if there is no GROUP BY), the database does the following:
- Reads the value of
xfor every input row. - Discards NULLs.
- Removes duplicate values, usually by sorting the values or by building a hash set.
- Counts what remains.
Step 3 is where the cost lies. A plain COUNT(*) only needs a running total. COUNT(DISTINCT x) must remember or sort every distinct value it has seen. On a column with millions of different values, this uses memory or spills to disk. An index on the column can help, because an index already holds the values in sorted order and lets the database skip over repeats.
The diagram below shows the steps.
NULL values are ignored
COUNT(DISTINCT column) never counts NULL. This is the most common surprise with the function.
Suppose customers has these country values: 'US', 'US', 'DE', NULL, NULL.
COUNT(*)returns 5.COUNT(country)returns 3.COUNT(DISTINCT country)returns 2.
Compare this with SELECT DISTINCT country. That query returns three rows, because DISTINCT treats all NULLs as one group and keeps one NULL row. So the number of rows from SELECT DISTINCT country can be one larger than COUNT(DISTINCT country).
If you want NULL to count as its own value, convert it to a placeholder first:
SELECT COUNT(DISTINCT COALESCE(country, 'unknown')) AS country_count
FROM customers;Choose a placeholder that cannot clash with a real value. If a real country were stored as 'unknown', the two would merge.
An alternative that avoids the placeholder is to add one for the NULL case:
SELECT COUNT(DISTINCT country)
+ MAX(CASE WHEN country IS NULL THEN 1 ELSE 0 END) AS country_count
FROM customers;The MAX(CASE ...) part is 1 if at least one NULL exists and 0 otherwise. This is longer, so use it only when a safe placeholder is hard to find.
Counting within groups
COUNT(DISTINCT) is most useful with GROUP BY. This query counts how many different customers placed orders in each month:
SELECT
SUBSTR(CAST(order_date AS VARCHAR(10)), 1, 7) AS order_month,
COUNT(*) AS order_count,
COUNT(DISTINCT customer_id) AS active_customers
FROM orders
GROUP BY SUBSTR(CAST(order_date AS VARCHAR(10)), 1, 7)
ORDER BY order_month;The month expression is written with SUBSTR and CAST because these work in most systems. Many databases have a shorter date function, such as DATE_TRUNC in PostgreSQL or strftime in SQLite.
Here order_count counts orders and active_customers counts people. A customer who places three orders in March adds 3 to order_count and 1 to active_customers. Putting both in one query makes the difference easy to see, and it shows why the two numbers should not be confused.
Multiple columns: a common error
SELECT DISTINCT country, city treats the pair as the unit. You might expect the same from COUNT(DISTINCT country, city). Support for that form varies:
- MySQL accepts
COUNT(DISTINCT country, city)and counts distinct pairs. A pair with a NULL in either column is skipped. - PostgreSQL, SQL Server, and SQLite reject it with a syntax error.
A portable way is to count the rows of a DISTINCT subquery:
SELECT COUNT(*) AS location_count
FROM (
SELECT DISTINCT country, city
FROM customers
) AS locations;There is one difference to watch. The subquery keeps rows where only one of the two columns is NULL, and it keeps rows where both are NULL as a single row. So COUNT(*) over the subquery counts those rows, while MySQL's multi-column form skips them. If NULLs are possible, filter them out explicitly with WHERE country IS NOT NULL AND city IS NOT NULL inside the subquery when you want the MySQL behavior.
Another option is to concatenate the columns into one value, but this is risky. With a separator-free join, 'ab' || 'c' and 'a' || 'bc' both give 'abc'. A concatenation also gives NULL if either part is NULL in most systems. Prefer the subquery.
Using DISTINCT inside other aggregates
DISTINCT is not limited to COUNT. It can appear in any standard aggregate:
SELECT
SUM(DISTINCT total) AS sum_of_distinct_totals,
SUM(total) AS sum_of_totals
FROM orders;SUM(DISTINCT total) adds each different order total once. If two orders both have a total of 20.00, the first sum includes 20.00 once and the second includes it twice. This is rarely what you want. Two different orders with the same amount are not duplicates in any business sense. Use DISTINCT inside an aggregate only when the repeated values really are repeats of the same fact. This often happens after a join, as the next section explains.
Joins that inflate counts
A common reason to use COUNT(DISTINCT) is a join that repeats rows. If each customer has many orders, joining customers to orders repeats each customer once per order:
SELECT
c.country,
COUNT(*) AS joined_rows,
COUNT(DISTINCT c.customer_id) AS customers_with_orders
FROM customers AS c
JOIN orders AS o
ON o.customer_id = c.customer_id
GROUP BY c.country
ORDER BY c.country;joined_rows counts customer-order pairs, so it equals the number of orders. customers_with_orders counts each customer once. Use the second form whenever the question is about customers rather than orders.
Be careful with the opposite mistake. Adding DISTINCT to hide an unexpected multiplication can mask a join condition that is wrong. If a count looks too high, check the join first and add DISTINCT only when the repetition is expected.
Performance and alternatives
COUNT(DISTINCT) is more expensive than COUNT(*). Keep these points in mind:
- On large tables, the database sorts or hashes every value in each group. Memory use grows with the number of different values.
- An index on the counted column can allow the planner to read values in order and skip repeats.
- Several
COUNT(DISTINCT)expressions in one query may each need their own sort or hash step. In some systems, this makes the query much slower than one with a single distinct count. - Some systems offer approximate functions, such as
APPROX_COUNT_DISTINCTin SQL Server and Snowflake, or HyperLogLog extensions in PostgreSQL. These use far less memory and give results within a small error. They suit dashboards and estimates, not billing or audits.
Edge cases
- Empty input. On an empty table,
COUNT(DISTINCT x)returns 0, not NULL. This differs fromSUM, which returns NULL for no rows. - Case and spaces.
'US','us', and'US 'are different values in most collations. Case-insensitive collations, such as the default in MySQL and SQL Server, treat'US'and'us'as equal. Trailing spaces may also be ignored. Clean the data or applyUPPER(TRIM(country))inside the function when the data is inconsistent. - Type differences.
COUNT(DISTINCT total)compares numbers by value, so20.0and20.00are one value. Floating-point columns can hold values that print the same but differ in the last bits, which makes them count separately. - Combining with LIMIT.
COUNT(DISTINCT x)withoutGROUP BYreturns one row, soLIMIThas no effect on it. WithGROUP BY,LIMITrestricts the number of groups returned, not the number of values counted. AddORDER BYso the groups you keep are predictable.
Putting it together
This query lists the five countries with the most distinct buying customers. It combines the join, the distinct count, ordering, and a limit:
SELECT
c.country,
COUNT(DISTINCT c.customer_id) AS buyers
FROM customers AS c
JOIN orders AS o
ON o.customer_id = c.customer_id
GROUP BY c.country
ORDER BY buyers DESC, c.country
LIMIT 5;Sorting by c.country after buyers breaks ties, so the same five rows come back on every run. This is the same determinism rule you will see again with LIMIT.
Exercise
A table visits has a column visitor_id with the values 7, 7, 9, NULL, NULL, 12. What do COUNT(*), COUNT(visitor_id), and COUNT(DISTINCT visitor_id) return, and how many rows does SELECT DISTINCT visitor_id FROM visits return?
Show answer
COUNT(*) returns 6, because it counts every row. COUNT(visitor_id) returns 4, because it skips the two NULLs and keeps both 7s. COUNT(DISTINCT visitor_id) returns 3, because the distinct non-NULL values are 7, 9, and 12. SELECT DISTINCT visitor_id returns 4 rows: 7, 9, 12, and one NULL row.
Exercise
Write a query that returns the number of different cities in customers, counting each city name once even if it appears in several countries, and counting customers with no city as one extra "unknown" city. Then explain why COUNT(DISTINCT city) alone would give a lower number when some cities are NULL.
Show answer
SELECT COUNT(DISTINCT COALESCE(city, 'unknown')) AS city_count FROM customers; Plain COUNT(DISTINCT city) ignores NULL, so customers with no city add nothing to the count. The COALESCE call replaces NULL with 'unknown' before the distinct step, so all of those customers add exactly one value.
Exercise
A report joins customers to orders and shows 12,400 for COUNT(*) and 3,100 for COUNT(DISTINCT c.customer_id). What does each number mean, and which one answers "how many customers have ordered?"
Show answer
12,400 is the number of joined customer-order rows, which equals the number of orders for customers that have at least one. 3,100 is the number of different customers in those rows. The second number answers the question, because the join repeats each customer once per order.