SQL APPROX_COUNT_DISTINCT function
Counts distinct values with bounded error and fixed memory instead of exact counting.
- Kategorie
- Aggregates
- Returns
bigint- In this category
- 34 of 52
Syntax
APPROX_COUNT_DISTINCT(x)
Engine-Unterstützung
| Engine | Support | Notizen |
|---|---|---|
| SQL Server | Ja | about 2% error guarantee, since SQL Server 2019 |
| PostgreSQL | Not built in | no built-in; the HLL extension fills the gap |
| MySQL | Not built in | no built-in; use COUNT(DISTINCT) |
| SQLite | Not built in | No built-in equivalent. |
| Oracle | Ja | 12.1.0.2+ |
Beispiele
SQL Server
SELECT APPROX_COUNT_DISTINCT(visitor_id) FROM hits WHERE day = '2026-11-19';
Oracle
SELECT APPROX_COUNT_DISTINCT(session_id) FROM events;
Gut zu wissen
- The SQL Server guarantee is statistical: 97% of results land within 2% of the true count, never a promise of exactness.
- It streams with constant memory, which is why it wins on huge, high-cardinality sets where COUNT(DISTINCT) spills or times out.
- PostgreSQL has no built-in; HyperLogLog extensions or sampling fill the gap.
- Never use it for billing, deduplication or anything a user will check by hand.
Questions about APPROX_COUNT_DISTINCT
How accurate is APPROX_COUNT_DISTINCT?
SQL Server guarantees about 2% error with 97% probability; Oracle is similar in spirit but treat both as estimates.
Why is it faster than COUNT(DISTINCT)?
It never builds the full distinct set: fixed-memory sketches replace the sort or hash of every value.
Does PostgreSQL have it?
Not built-in; use a HyperLogLog extension or accept exact COUNT(DISTINCT).
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, 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.