// aggregates reference

SQL COUNT(DISTINCT) function

Counts the unique non-null values of an expression in a group: distinct customers, distinct countries, distinct error codes.

カテゴリ
Aggregates
Returns
integer
In this category
6 of 52

構文

COUNT(DISTINCT expression)

エンジンサポート

エンジンSupportメモ
SQL Server はい Supported under this name.
PostgreSQL はい Supported under this name.
MySQL はい Supported under this name.
SQLite はい Supported under this name.
Oracle はい Supported under this name.

例

Any engine

SELECT COUNT(DISTINCT customer_id) AS paying_customers
FROM orders;

SQL Server

SELECT APPROX_COUNT_DISTINCT(session_id) AS approx_sessions
FROM events;

知っておくと便利なこと

  • NULL is never counted, even once: a column of NULLs counts as zero distinct values.
  • Exact distinct counting keeps every distinct value it has seen, so memory grows with the number of distinct values, not the number of rows.
  • Approximate counters trade a small error for far less memory: APPROX_COUNT_DISTINCT on SQL Server 2019+ and Oracle 12c+. PostgreSQL needs an extension such as postgresql-hll; MySQL and SQLite have none.
  • MySQL also accepts several expressions: COUNT(DISTINCT customer_id, product_id) counts distinct pairs.

Questions about COUNT(DISTINCT)

Does COUNT(DISTINCT) count NULL?

No. NULLs are dropped before counting. If the column holds NULLs, COUNT(DISTINCT col) is exactly one less than COUNT(DISTINCT COALESCE(col, 'unknown')), assuming 'unknown' is not already a value.

Can I count distinct pairs, like customer and product?

MySQL takes both columns directly: COUNT(DISTINCT customer_id, product_id). PostgreSQL accepts a row value: COUNT(DISTINCT (customer_id, product_id)). Elsewhere count distinct rows of a subquery: SELECT COUNT(*) FROM (SELECT DISTINCT customer_id, product_id FROM orders) t. Gluing the columns into one string works too, but only with a separator that cannot appear in the data.

Why is COUNT(DISTINCT) slow?

It has to sort or hash every value to remove duplicates before counting. On SQL Server and Oracle, APPROX_COUNT_DISTINCT answers within a few percent using much less memory.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.