SQL COUNT(DISTINCT) function
Counts the unique non-null values of an expression in a group: distinct customers, distinct countries, distinct error codes.
- Catégorie
- Aggregates
- Returns
integer- In this category
- 6 of 52
Syntaxe
COUNT(DISTINCT expression)
Prise en charge des moteurs
| Moteur | Support | Notes |
|---|---|---|
| SQL Server | Oui | Supported under this name. |
| PostgreSQL | Oui | Supported under this name. |
| MySQL | Oui | Supported under this name. |
| SQLite | Oui | Supported under this name. |
| Oracle | Oui | Supported under this name. |
Exemples
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;
Bon à savoir
- 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.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
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.