Quick revision
The short answer
Databases execute DISTINCT with a hash aggregate, which keeps every distinct value seen in a hash table, or with a sort followed by a pass that drops repeated neighbours; an index can supply sorted input instead. COUNT(DISTINCT user_id) must remember every distinct value per group, so over a billion rows its memory grows with the number of distinct users and it spills to disk once work memory is exceeded. HyperLogLog sketches give an approximate count in a few kilobytes with an error of about 1 to 2 percent, and daily sketches can be combined for rollups.
What to remember
In this answer, we saw that DISTINCT is computed with a hash aggregate or a sort followed by a unique pass, and that both must remember every distinct value, so COUNT(DISTINCT user_id) over a billion rows grows with cardinality and spills to disk past work memory. Indexes can provide sorted input, and skipping between values helps only for low-cardinality columns, through a loose index scan in MySQL or a recursive CTE in PostgreSQL. HyperLogLog gives approximate distinct counts in fixed small memory, and daily sketches can be merged for any rollup.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Databases execute DISTINCT with a hash aggregate, which keeps every distinct value seen in a hash table, or with a sort followed by a pass that drops repeated neighbours; an index can supply sorted input instead. COUNT(DISTINCT user_id) must remember every distinct value per group, so over a billion rows its memory grows with the number of distinct users and it spills to disk once work memory is exceeded. HyperLogLog sketches give an approximate count in a few kilobytes with an error of about 1 to 2 percent, and daily sketches can be combined for rollups.
Why this question is asked
Counting unique users, unique sessions or unique devices is at the heart of almost every product dashboard, and it is one of the first queries to fall over as data grows. Interviewers ask about it to see whether we understand that distinctness is a memory problem, not just a CPU problem, and whether we know when an exact answer is worth its cost. In this answer, we will see the two ways a database removes duplicates, why COUNT(DISTINCT) is harder than COUNT, how indexes and skip scans help, and how approximate counting and pre-aggregation make the billion-row case cheap.
1A Quick Recap: Removing Duplicates Means Remembering
COUNT(*) only needs one number, a running total, however many rows it reads. To know whether a value is new, by contrast, the database must remember all the values it has already seen. That is the whole difficulty of DISTINCT in one sentence: the memory it needs grows with cardinality, the number of different values, not with the number of rows.
There are two classic algorithms. A hash aggregate inserts each value into a hash table and ignores values already present. A sort-based plan sorts all values so that equal ones sit next to each other, then a single pass emits each value once, which PostgreSQL shows as Sort followed by Unique.
2What the Plans Look Like
Here is a query over an events table with 1 billion rows and about 40 million distinct user_id values, with the shape of the PostgreSQL plan in comments.
| Method | Memory | Notes |
|---|---|---|
| Hash aggregate | grows with distinct values | fast when the set fits in work memory |
| Sort + unique pass | grows with rows; spills to external sort | output comes out sorted |
| Index scan in key order | constant | reads every index entry unless it can skip |
| Loose index scan / skip | constant | jumps from one value to the next; low cardinality |
HyperLogLog sketch | fixed, a few KB | approximate, about 1 to 2 percent error |
The hash table for 40 million 8-byte ids plus per-entry overhead needs a few gigabytes. PostgreSQL limits the memory of each hash or sort operation by work_mem, multiplied by hash_mem_multiplier for hashes, and since version 13 a hash aggregate that exceeds it splits its input into batches on disk. A sort that exceeds it becomes an external merge sort, writing sorted runs to temporary files and merging them. Both still work, but disk I/O replaces memory and the query takes minutes.
PostgreSQL traditionally evaluates an aggregate with DISTINCT inside it by sorting its input, as the second plan shows, rather than hashing, and recent versions can reuse input that is already sorted. MySQL uses a temporary table with a unique index for COUNT(DISTINCT), which also spills to disk when it grows past its in-memory limit.
3How an Index Helps, and Skipping Duplicates
A B-tree index on user_id stores the values in sorted order, so the database can read the index instead of sorting, and the unique pass becomes a cheap streaming step. That saves the sort but still reads every one of the billion index entries.
The real win is skipping. If a column has few distinct values, say 200 countries in a billion rows, an ideal plan jumps from the first entry of one value straight to the first entry of the next, touching about 200 places in the index. MySQL calls this a loose index scan and uses it for some DISTINCT and GROUP BY queries. PostgreSQL does not do this for DISTINCT natively in the versions most of us run; PostgreSQL 18 added a B-tree skip scan, but it targets multicolumn indexes whose leading column is not filtered, so check your version for what applies to DISTINCT. The classic workaround is a recursive CTE that asks for the next larger value each time.
Each step of the recursion is one index lookup for the next value. This is excellent for low-cardinality columns and useless for 40 million user ids, where it would perform 40 million lookups.
4Approximate Counting With HyperLogLog
For dashboards, the difference between 40,112,507 and 40,500,000 unique users rarely matters, while the difference between a two-second and a twenty-minute query does. HyperLogLog, HLL for short, is an algorithm that estimates the number of distinct values using a small fixed array of registers. It hashes each value and records, per register, the longest run of leading zero bits it has seen; long runs are rare, so they reveal roughly how many distinct values passed by. The standard error is about 1.04 divided by the square root of the number of registers, so 4,096 registers, a few kilobytes, give roughly 1.6 percent, whether there are a thousand or a billion users.
Many systems offer it built in: APPROX_COUNT_DISTINCT in several warehouses and in SQL Server, APPROX_COUNT_DISTINCT or HLL functions in BigQuery and Snowflake. In PostgreSQL it comes from extensions such as postgresql-hll.
5Pre-Aggregating Sketches for Rollups
The second property of HLL is what makes it fit reporting: two sketches can be merged, and the merged sketch estimates the distinct count of the union. Exact distinct counts cannot be added up; users active on Monday plus users active on Tuesday is not users active on both days. Sketches can.
- Raw events, 1 billion rowsread once per day
- One HLL sketch per daya few KB each
- Merge sketches for the rangeweek, month, year
- Estimate distinct usersabout 1 to 2 percent error
4 steps in order. Play them, or step through them one at a time.
Each day's raw events are read once, and every later report reads only 30 or 365 sketches of a few kilobytes each. If a report truly needs an exact answer, for example for billing, the equivalent exact technique is to keep a pre-aggregated table of distinct (day, user_id) pairs and count from that, which is much smaller than raw events but still grows with users per day.
6Follow-up questions
Why can I not just add daily distinct counts to get a monthly count?
Because the same user is active on many days. If 1 million users are active every day of June, the daily counts add up to 30 million, while the monthly distinct count is 1 million. Only a structure that remembers identities, or a mergeable sketch like HLL, can combine periods.
Would raising work_mem fix the slow COUNT(DISTINCT)?
It can stop the spill to disk for one query, but work_mem applies per operation and per parallel worker, so setting it to several gigabytes globally risks running the server out of memory under load. Raising it for one reporting session is reasonable; making it the fix for a growing dashboard is not.
When is an approximate count unacceptable?
When the number has a contractual or financial meaning, such as billing per active user, or when small groups matter, since a 2 percent error on 50 users is noticeable. There we use exact pre-aggregated tables and accept the extra storage.
7Conclusion
In this answer, we saw that DISTINCT is computed with a hash aggregate or a sort followed by a unique pass, and that both must remember every distinct value, so COUNT(DISTINCT user_id) over a billion rows grows with cardinality and spills to disk past work memory. Indexes can provide sorted input, and skipping between values helps only for low-cardinality columns, through a loose index scan in MySQL or a recursive CTE in PostgreSQL. HyperLogLog gives approximate distinct counts in fixed small memory, and daily sketches can be merged for any rollup.
Open with
A database removes duplicates in one of two ways: a hash aggregate that keeps every value it has seen in a hash table, or a sort that puts equal values next to each other followed by a pass that keeps one of each.
Then, if they want more
An index on the column can supply already sorted input. The key point is that distinctness needs memory proportional to the number of distinct values. COUNT star needs one counter, but COUNT DISTINCT user_id has to remember every user id it has seen, per group.
With a billion rows and tens of millions of users, that does not fit in work_mem, so PostgreSQL spills the hash into batches on disk or does an external merge sort, and the query takes minutes.
For low-cardinality columns, skipping from one value to the next in the index helps: MySQL has a loose index scan, and in PostgreSQL I can emulate it with a recursive CTE, though I would check the version for native skip scan support.
For unique users at scale, I would use HyperLogLog: a sketch of a few kilobytes estimates the distinct count with about one to two percent error regardless of size, through warehouse functions like APPROX_COUNT_DISTINCT or the postgresql-hll extension.
The best part is that sketches merge, so I build one sketch per day and union them for weekly or monthly unique users, which exact daily counts cannot do.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- PostgreSQL 18
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- PostgreSQL documentation, The SQL Language
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "How do databases execute DISTINCT and COUNT(DISTINCT col) internally, and why is...": https://scrivio-interview-library.netlify.app/databases/sql-fundamentals/82e4986cd6/