Recipe · SQL recipes

COUNT(DISTINCT) on multiple columns in SQL

To count distinct combinations, first run SELECT DISTINCT on the columns and then count the rows that subquery returns.

Query

The teaching database has 12 customers, 6 distinct cities and 7 distinct combinations of city and active. London has both active and inactive customers, so it adds two combinations even though it is a single city.

SQLite · run on the teaching database
SELECT COUNT(*) AS distinct_combinations
FROM (
  SELECT DISTINCT city, active
  FROM customers
) AS combinations;

To see what the query is really counting, run just the inner part:

Look at the combinations before counting them
SELECT DISTINCT city, active
FROM customers
ORDER BY city, active;

How it works

COUNT(DISTINCT city) counts distinct cities. Add another column and the question changes: you are no longer after unique cities but unique combinations such as (London, active) and (London, inactive).

Mental model: treats the chosen columns as a temporary composite key. Two rows count as the same combination only when they match on every one of those columns.

Cases that change the result

Engine-specific shortcuts are not interchangeable when any column can contain NULL. The MySQL documentation states that its multi-expression form counts only combinations that contain no NULL. If you need to keep combinations where one of the columns is null, the pattern with SELECT DISTINCT makes those rows visible before counting and is easier to check.

In this example, city and active are non-null columns, so all three forms shown return the same total of 7 on the engines that support their syntax.

Key differences between engines

The pattern with SELECT DISTINCT inside a subquery is easy to read and works in PostgreSQL, MySQL, SQL Server and SQLite. Some engines also offer a shorthand, but the syntax is not the same.

PostgreSQL

PostgreSQL lets you build a row value and pass it to the aggregate as a single expression:

PostgreSQL
SELECT COUNT(DISTINCT (city, active))
FROM customers;

MySQL

MySQL accepts several expressions directly inside COUNT(DISTINCT ...):

MySQL 8.4
SELECT COUNT(DISTINCT city, active)
FROM customers;

SQL Server and SQLite

The documented syntax of COUNT(DISTINCT expresión) takes a single expression. To count combinations without inventing your own encoding, use the subquery with SELECT DISTINCT and then COUNT(*).