Coding

Count in SQL: COUNT(*), COUNT(column) and COUNT(DISTINCT) Examples

Count in SQL is done with the COUNT aggregate function: SELECT COUNT(*) FROM orders; returns the number of rows, while COUNT(column) counts only rows where that column is not NULL and COUNT(DISTINCT column) counts unique non-NULL values. Add GROUP BY to get one count per group and HAVING to filter on those counts.

The examples below use one small table, so you can check every result by hand. They follow standard SQL and run on PostgreSQL, MySQL and SQL Server unless a section says otherwise.

The sample table

CREATE TABLE orders (
  id       INT PRIMARY KEY,
  customer VARCHAR(20) NOT NULL,
  status   VARCHAR(20) NOT NULL,
  coupon   VARCHAR(20)          -- NULL when no coupon was used
);

INSERT INTO orders (id, customer, status, coupon) VALUES
  (1, 'Ana',  'shipped',   'SAVE5'),
  (2, 'Ana',  'shipped',   NULL),
  (3, 'Ben',  'pending',   NULL),
  (4, 'Cleo', 'shipped',   'SAVE5'),
  (5, 'Cleo', 'cancelled', NULL),
  (6, 'Cleo', 'shipped',   'SAVE10');

Six rows, three customers, and three rows with a coupon. Those three facts are what the counts below turn on.

COUNT(*): count all rows

SELECT COUNT(*) FROM orders;

Example output:

count
-----
    6

COUNT(*) counts rows. It does not look at any column, so NULLs cannot affect it. Microsoft's documentation says it "counts each row separately, including rows that contain null values", and that it preserves duplicate rows. PostgreSQL describes it as computing "the number of input rows". Add a WHERE clause to count a subset:

SELECT COUNT(*) FROM orders WHERE status = 'shipped';

Example output: 4. WHERE runs before the aggregate, so only the four shipped rows reach COUNT.

COUNT(column): skip NULLs

SELECT COUNT(coupon) FROM orders;

Example output: 3. Rows 2, 3 and 5 have a NULL coupon, so they are skipped. MySQL's manual puts it as "a count of the number of non-NULL values of expr", and PostgreSQL as "the number of input rows in which the input value is not null".

This is the most common surprise with COUNT. If you want to know how many rows are missing a value, subtract, or filter on IS NULL:

SELECT COUNT(*) - COUNT(coupon) AS orders_without_coupon FROM orders;
-- or
SELECT COUNT(*) FROM orders WHERE coupon IS NULL;

Both return 3. Don't write WHERE coupon = NULL: comparing anything to NULL with = is never true, so it matches no rows. The same three-valued logic is behind the traps in SQL not equal operators and the NULL trap.

COUNT(DISTINCT column): count unique values

SELECT COUNT(DISTINCT customer) AS customers,
       COUNT(DISTINCT coupon)   AS coupons_used
FROM orders;

Example output:

customers | coupons_used
----------+-------------
        3 |            2

There are six orders but three distinct customers. For coupons, SAVE5 appears twice and counts once, SAVE10 counts once, and the NULLs are ignored, giving 2. PostgreSQL's documentation says count(distinct f1) yields the number of distinct non-null values, and Microsoft's says the same for SQL Server.

COUNT(DISTINCT *) is not valid. Microsoft's reference states that COUNT(*) "doesn't support the use of DISTINCT". To count distinct combinations of columns, the portable way is a subquery:

SELECT COUNT(*)
FROM (SELECT DISTINCT customer, status FROM orders) AS combos;

Example output: 4. The combinations are Ana/shipped, Ben/pending, Cleo/shipped and Cleo/cancelled. SQL Server's COUNT takes a single expression, so the subquery is the form that works there. MySQL's manual says you can give COUNT(DISTINCT ...) a list of expressions, but it counts only combinations that contain no NULL.

COUNT with GROUP BY: one count per group

SELECT customer, COUNT(*) AS order_count
FROM orders
GROUP BY customer
ORDER BY customer;

Example output:

customer | order_count
---------+------------
Ana      |           2
Ben      |           1
Cleo     |           3

Microsoft's reference describes COUNT(*) with GROUP BY as returning "the number of rows in each group". Every column in the SELECT list must be either in GROUP BY or inside an aggregate. The same pattern works on any column, for example GROUP BY status returns shipped 4, pending 1 and cancelled 1.

COUNT with HAVING: filter on the count

WHERE cannot see an aggregate, because it runs before grouping. To keep only groups whose count meets a condition, use HAVING:

SELECT customer, COUNT(*) AS order_count
FROM orders
GROUP BY customer
HAVING COUNT(*) > 1;

Example output: Ana with 2 and Cleo with 3. Ben has one order and is dropped. Microsoft's reference has an example of the same shape, returning departments with more than 15 employees.

A useful variation finds duplicates: group by the column that should be unique and keep groups with HAVING COUNT(*) > 1.

Conditional counts: count rows that meet a condition

To get several counts in one pass, put a CASE expression inside COUNT. CASE returns NULL when no branch matches, and COUNT(expression) skips NULLs, so only matching rows are counted:

SELECT COUNT(*)                                          AS total,
       COUNT(CASE WHEN status = 'shipped' THEN 1 END)    AS shipped,
       COUNT(CASE WHEN status = 'pending' THEN 1 END)    AS pending
FROM orders;

Example output:

total | shipped | pending
------+---------+--------
    6 |       4 |       1

Don't use ELSE 0 here. Zero is not NULL, so every row would be counted. Use SUM(CASE WHEN ... THEN 1 ELSE 0 END) if you prefer to add ones and zeros.

PostgreSQL also has a shorter form, FILTER. Its documentation says that only the rows for which the filter condition is true are fed to the aggregate:

SELECT COUNT(*) AS total,
       COUNT(*) FILTER (WHERE status = 'shipped') AS shipped
FROM orders;

Example output: 6 and 4. This syntax comes from the PostgreSQL manual. SQL Server and MySQL don't document this clause on the pages cited here, so use CASE there.

What COUNT returns when nothing matches

SELECT COUNT(*) FROM orders WHERE status = 'refunded';

Example output: 0. A query with an aggregate and no GROUP BY always returns exactly one row, and for COUNT that row holds zero. PostgreSQL's manual notes that count is the exception among aggregates: the others return NULL when no rows are selected. With GROUP BY, an empty input produces no groups, so you get no rows at all rather than a row of zeros.

The same rule matters for joins. Counting a column from the right side of a LEFT JOIN gives 0 for unmatched rows, while COUNT(*) gives 1, because the unmatched row itself still exists. SQL joins explained shows this with real output.

COUNT(1), COUNT(*) and speed

COUNT(1) counts a constant that is never NULL, so it returns the same number as COUNT(*). MySQL's manual states that InnoDB handles COUNT(*) and COUNT(1) in the same way, with no performance difference. Use COUNT(*): it says what it does.

Speed depends on the engine. PostgreSQL's manual warns that SELECT count(*) FROM sometable; takes effort proportional to the size of the table. In MySQL, InnoDB keeps no internal row count, because concurrent transactions can see different numbers of rows, so it traverses the smallest available secondary index or scans the clustered index. Only MyISAM stores an exact count and can answer an unfiltered single-table COUNT(*) instantly. On a large table, an exact count is a real scan. If an approximate figure is enough, MySQL's manual points to SHOW TABLE STATUS.

COUNT as a window function

Adding OVER turns COUNT into a window function, which keeps every row and attaches the count to each one:

SELECT id, customer,
       COUNT(*) OVER (PARTITION BY customer) AS customer_orders
FROM orders
ORDER BY id;

Example output:

id | customer | customer_orders
---+----------+----------------
 1 | Ana      |               2
 2 | Ana      |               2
 3 | Ben      |               1
 4 | Cleo     |               3
 5 | Cleo     |               3
 6 | Cleo     |               3

Microsoft's reference gives the syntax COUNT ( { [ ALL ] expression | * } ) OVER ( [ partition_by_clause ] ) and notes that without a partition clause all rows of the result are one group. MySQL says each COUNT form runs as a window function when an OVER clause is present.

If COUNT overflows in SQL Server

SQL Server's COUNT always returns int, with a maximum of 2,147,483,647. A bigger result fails, and the documented error is:

Msg 8115, Level 16, State 2; Arithmetic overflow error converting expression to data type int.

Switch to COUNT_BIG, which takes the same arguments and returns bigint. PostgreSQL and MySQL already return bigint from count, so they don't have this limit.

Frequently asked questions

What is the difference between COUNT(*) and COUNT(column)?
COUNT(*) counts every row in the group, including rows where all columns are NULL. COUNT(column) counts only the rows where that column is not NULL. If the column has no NULLs, both return the same number.
Does COUNT include NULL values?
Only COUNT(*) does, because it counts rows rather than values. COUNT(column), COUNT(DISTINCT column) and COUNT(expression) ignore NULLs, as all SQL aggregate functions do except COUNT(*).
What does COUNT return when there are no matching rows?
Zero. In PostgreSQL's documentation, count is the only aggregate that returns zero rather than NULL when no rows are selected, and MySQL documents the same result for COUNT and COUNT(DISTINCT). SUM, AVG, MIN and MAX return NULL on an empty set.
Why does COUNT fail with an arithmetic overflow error in SQL Server?
In SQL Server, COUNT always returns an int, whose maximum is 2,147,483,647. A larger result raises error 8115, Arithmetic overflow error converting expression to data type int. Use COUNT_BIG, which returns bigint.

Sources