// aggregates reference

SQL DISTINCT aggregates

Aggregates that drop duplicate values before counting, summing or averaging.

Categoría
Aggregates
Returns
numeric or string
In this category
46 of 52

Sintaxis

COUNT(DISTINCT x) | AVG(DISTINCT x) | GROUP_CONCAT(DISTINCT x)

Soporte del motor

MotorSupportNotas
SQL Server Sí Supported under this name.
PostgreSQL Sí Supported under this name.
MySQL Sí Supported under this name.
SQLite Sí Supported under this name.
Oracle Sí Supported under this name.

Ejemplos

Any engine

SELECT COUNT(DISTINCT customer_id) FROM orders;

PostgreSQL

SELECT COUNT(DISTINCT (order_id, product_id)) FROM line_items;

MySQL

SELECT GROUP_CONCAT(DISTINCT tag ORDER BY tag) FROM posts;

Conviene saberlo

  • AVG(DISTINCT x) divides by the number of unique values, not rows, almost never what you want; dedupe upstream instead.
  • Counting distinct pairs: MySQL accepts COUNT(DISTINCT a, b) and skips any pair containing a NULL; PostgreSQL needs the row form COUNT(DISTINCT (a, b)); SQL Server, Oracle and SQLite need a subquery or a concatenated key.
  • SQLite allows DISTINCT only on one-argument aggregates, so GROUP_CONCAT(DISTINCT x, ';') is a parse error. PostgreSQL requires ORDER BY expressions in a DISTINCT aggregate to appear in its argument list; MySQL's GROUP_CONCAT(DISTINCT a ORDER BY b) is allowed.
  • Exact DISTINCT counting is memory-hungry at scale; that is what APPROX_COUNT_DISTINCT trades accuracy against.

Questions about DISTINCT

Can I use DISTINCT across two columns?

MySQL: COUNT(DISTINCT a, b) counts distinct pairs; PostgreSQL: COUNT(DISTINCT (a, b)); SQL Server, Oracle and SQLite: SELECT COUNT(*) FROM (SELECT DISTINCT a, b FROM t) d.

Is SUM(DISTINCT) ever useful?

Rarely: it sums each value once. If you meant deduplicated rows, you usually want a subquery or a join instead.

Why is COUNT(DISTINCT) slow on big tables?

It must build the full distinct set; an index on the column helps, or APPROX_COUNT_DISTINCT (SQL Server, Oracle) when a few percent of error is fine.

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.