Sub topic 3
COUNT(*), COUNT(column) and COUNT(DISTINCT)
This chapter assumes you can write basic SELECT, FROM, WHERE and ORDER BY queries. It also assumes you know that NULL means a missing value, and that you have seen the aggregate functions COUNT, SUM, AVG, MIN and MAX once. The previous chapter showed that most aggregates skip NULL. COUNT is different, because it comes in three forms that answer three different questions.
The three forms at a glance
All examples use an orders table. Each row is one order. The column customer_id identifies who placed it. The column shipped_at holds a timestamp, and it is NULL until the order ships.
| Form | What it counts | NULL handling |
|---|---|---|
| `COUNT(*)` | Rows in the group | Counts every row, whatever its values |
| `COUNT(column)` | Rows where the column is not NULL | Skips rows where the column is NULL |
| `COUNT(DISTINCT column)` | Different non-NULL values of the column | Skips NULL, then removes duplicates |
Here is a small sample of orders that the rest of the chapter uses.
| order_id | customer_id | amount | status | shipped_at |
|---|---|---|---|---|
| 1 | 10 | 120.00 | paid | 2026-11-01 |
| 2 | 10 | 80.00 | paid | NULL |
| 3 | 11 | 200.00 | refunded | 2026-11-03 |
| 4 | 11 | 50.00 | paid | 2026-11-04 |
| 5 | 11 | 75.00 | paid | NULL |
| 6 | NULL | 30.00 | paid | NULL |
Order 6 has no customer. That could be a guest checkout. It is useful here because it shows how NULL behaves.
One query, three answers
SELECT COUNT(*) AS all_orders,
COUNT(shipped_at) AS shipped_orders,
COUNT(DISTINCT customer_id) AS distinct_customers
FROM orders;On the sample data the result is one row:
| all_orders | shipped_orders | distinct_customers |
|---|---|---|
| 6 | 3 | 2 |
Each number comes from a different rule:
COUNT(*)returns 6 because the table has six rows.COUNT(shipped_at)returns 3 because only orders 1, 3 and 4 have a shipping timestamp. Orders 2, 5 and 6 are skipped.COUNT(DISTINCT customer_id)returns 2. The non-NULL values are 10, 10, 11, 11 and 11. After removing duplicates, 10 and 11 remain. Order 6 does not add a third customer, because NULL is not counted as a value.
COUNT(*): counting rows
COUNT(*) does not look at any column. The * here is not the "all columns" wildcard from SELECT *. It means "count the rows". A row with every column set to NULL still counts as one row.
Use COUNT(*) when the question is "how many rows are there?" For example, "how many orders did each customer place?" Every order is a row, so counting rows is correct.
COUNT(1) and COUNT(*) give the same result in every mainstream database. The 1 is a constant that is never NULL, so every row is counted. Most style guides prefer COUNT(*) because it states the intent directly. Performance is not a reason to choose between them. Optimizers treat them the same way.
COUNT(column): counting known values
COUNT(column) evaluates the expression for each row and counts the rows where the result is not NULL. This makes it useful as a "how many have this value filled in" counter.
SELECT COUNT(*) AS all_orders,
COUNT(shipped_at) AS shipped_orders,
COUNT(*) - COUNT(shipped_at) AS unshipped_orders
FROM orders;The difference COUNT(*) - COUNT(shipped_at) is the number of rows where shipped_at is NULL. This is a quick way to measure missing data in a column. You can compute it for several columns in one query, which makes a simple data-quality report.
A common mistake is to use COUNT(column) when you mean COUNT(*). If the column can contain NULL, your count will be too low, and no error appears. Pick the form from the question you are answering, not from habit.
COUNT(DISTINCT column): counting unique values
COUNT(DISTINCT customer_id) first discards NULL values, then removes duplicates, then counts what is left. It answers "how many different customers placed orders?" rather than "how many orders were placed?"
Compare these two queries:
SELECT COUNT(customer_id) AS orders_with_customer,
COUNT(DISTINCT customer_id) AS distinct_customers
FROM orders;On the sample data, orders_with_customer is 5 and distinct_customers is 2. The first number counts rows with a known customer. The second counts people.
You can also count distinct expressions. For example, COUNT(DISTINCT CAST(shipped_at AS DATE)) counts the distinct shipping days when shipped_at is a timestamp.
DISTINCT applies to one column or expression
In most databases, including PostgreSQL, MySQL and SQL Server for a single argument, COUNT(DISTINCT a, b) is not portable. PostgreSQL rejects the comma form. MySQL accepts it. SQL Server rejects it. If you need distinct pairs, use a portable approach such as a subquery:
SELECT COUNT(*) AS distinct_customer_status_pairs
FROM (
SELECT DISTINCT customer_id, status
FROM orders
) AS pairs;This subquery keeps the pair (NULL, paid) as one row, because DISTINCT treats NULLs as equal to each other. That differs from COUNT(DISTINCT ...), which ignores NULL. Keep this in mind when you compare results from the two styles.
Counting inside groups
All three forms work with GROUP BY. The rules do not change. They are applied separately to the rows of each group.
SELECT customer_id,
COUNT(*) AS order_count,
COUNT(shipped_at) AS shipped_count,
COUNT(DISTINCT status) AS status_kinds
FROM orders
GROUP BY customer_id
ORDER BY customer_id;On the sample data:
| customer_id | order_count | shipped_count | status_kinds |
|---|---|---|---|
| 10 | 2 | 1 | 1 |
| 11 | 3 | 2 | 2 |
| NULL | 1 | 0 | 1 |
Two details are worth noticing:
GROUP BYputs all NULL values into one group, so order 6 gets its own row. The NULL group is real output, even though NULL is not counted as a value byCOUNT(DISTINCT customer_id).- Customer 10 has
shipped_countof 1 even though they have 2 orders. The unshipped order is inorder_countbut not inshipped_count.
The position of the NULL row in the sorted output depends on the database. PostgreSQL and Oracle put NULL last in ascending order by default. MySQL and SQL Server put it first. Add NULLS LAST where it is supported, or sort on customer_id IS NULL first, if the position matters.
Counting an empty set
What does COUNT return when there are no rows? Run this query on the sample data:
SELECT COUNT(*) AS n,
COUNT(shipped_at) AS shipped,
SUM(amount) AS total
FROM orders
WHERE status = 'cancelled';No row has that status. The result is one row with n = 0, shipped = 0 and total = NULL. This is a useful contrast. COUNT returns 0 for an empty input, while SUM, AVG, MIN and MAX return NULL. If you display a SUM for an empty set and want a zero, wrap it in COALESCE(SUM(amount), 0).
This applies only when there is no GROUP BY. With GROUP BY and no matching rows, the query returns no rows at all, because there are no groups to report.
Choosing the right form
A practical way to choose is to say the question out loud and match its noun:
- "How many orders?" The noun is a row. Use
COUNT(*). - "How many orders have shipped?" The noun is a row with a value present. Use
COUNT(shipped_at), orCOUNT(*)withWHERE shipped_at IS NOT NULL. - "How many customers ordered?" The noun is a distinct entity. Use
COUNT(DISTINCT customer_id).
Edge cases and gotchas
DISTINCT is more expensive
COUNT(DISTINCT x) needs to remember which values it has already seen, usually by sorting or hashing. On a large table this costs more memory and time than COUNT(*). Some databases also handle several COUNT(DISTINCT ...) expressions in one query less efficiently. If you only need an estimate on huge data, many engines offer an approximate function, such as APPROX_COUNT_DISTINCT in SQL Server and Snowflake or approx_distinct in Trino. These names are not standard, so check your database.
COUNT(DISTINCT) does not add up across groups
If customer 11 appears in two different groups, the per-group distinct counts will count that customer twice when you add them. Distinct counts are not additive. The grand total must be computed with its own COUNT(DISTINCT ...) over the full set, not by summing group results.
Counting after a LEFT JOIN
When you join customers to their orders with a LEFT JOIN, customers with no orders still produce one row, with NULL in every order column. COUNT(*) would count that row and report 1. Count a column from the right-hand table instead.
SELECT c.customer_id,
c.name,
COUNT(o.order_id) AS order_count
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.customer_id
GROUP BY c.customer_id, c.name;Because o.order_id is NULL on the padding row, COUNT(o.order_id) returns 0 for customers with no orders. This pattern returns correct counts for customers with no orders. The join chapter covers the wider topic of fan-out when one row matches many.
The result type
COUNT returns an integer type. In PostgreSQL it is bigint, and in SQL Server COUNT returns int while COUNT_BIG returns bigint. For tables with more than about 2.1 billion rows, SQL Server's COUNT fails with an overflow error, so use COUNT_BIG there. Some client libraries return bigint as a string or a special number type, so check how your driver handles it.
Filtering inside a count
To count only some rows, you can use WHERE, which changes the rows for the whole query. To count different subsets side by side, use the FILTER clause where supported (PostgreSQL, SQLite) or a CASE expression inside the aggregate. The CASE form works everywhere:
SELECT COUNT(*) AS all_orders,
COUNT(CASE WHEN status = 'paid' THEN 1 END) AS paid_orders,
COUNT(CASE WHEN status = 'refunded' THEN 1 END) AS refunded_orders
FROM orders;The CASE has no ELSE, so non-matching rows produce NULL, and COUNT skips them. Writing ELSE 0 here would be a bug, because 0 is not NULL and every row would be counted. This technique is developed fully in the conditional aggregation chapter.
Summary of rules
COUNT(*)counts rows and never looks at values.COUNT(column)counts rows where the expression is not NULL.COUNT(DISTINCT column)ignores NULL, then counts unique values.- COUNT returns 0 on empty input, while SUM, AVG, MIN and MAX return NULL.
GROUP BYcreates a group for NULL keys, even thoughCOUNT(DISTINCT key)does not count NULL.- Distinct counts are not additive across groups.
Exercise
Using the sample orders table above, what do these three expressions return for the whole table: COUNT(*), COUNT(customer_id) and COUNT(DISTINCT status)? Then explain how you would count the customers who have at least one unshipped order.
Show answer
COUNT(*) is 6, because there are six rows. COUNT(customer_id) is 5, because order 6 has a NULL customerid. COUNT(DISTINCT status) is 2, because the distinct statuses are paid and refunded. To count customers with at least one unshipped order, filter first and then count distinct customers: SELECT COUNT(DISTINCT customerid) FROM orders WHERE shipped_at IS NULL; On the sample data this returns 2 (customers 10 and 11), because order 6 has a NULL customer and is not counted.
Exercise
A query uses LEFT JOIN from customers to orders, groups by customer, and reports COUNT(*) AS ordercount. A customer with no orders shows ordercount = 1. Why, and how do you fix it?
Show answer
The LEFT JOIN produces one padding row for that customer, with NULL in every orders column. COUNT() counts that row, so the result is 1. Replace COUNT() with COUNT(o.orderid), where o.orderid is a column from the orders side. It is NULL on the padding row and is skipped, so the count is 0.