Optimizing Slow GROUP BY, DISTINCT & ORDER BY Operations
Speed up sorts, distincts, and groups with indexes and rewrite tricks.
In plain words
Grouping and sorting are fast when rows come pre-sorted or when there are fewer of them to sort.
Think of it like…
Sorting a pile of exam papers by student: it's quick if they arrive already in alphabetical order (an index), slower if you have to sort them yourself, and much slower if the pile won't fit on your desk and you have to spread it across the floor (spilling to disk).
Where you’ve seen it
A marketing report ran SELECT DISTINCT c.id, c.email FROM customers c JOIN events e ON e.customer_id = c.id WHERE e.type = 'click', producing 60 million joined rows and a 40-second external sort just to return 900,000 customers. Rewriting it as WHERE EXISTS (SELECT 1 FROM events e WHERE e.customer_id = c.id AND e.type = 'click') returns the same customers with no DISTINCT, in 1.8 seconds.
Words you’ll hear
- Sort vs HashAggregate
- Two ways to group: sort rows then group neighbours, or build a hash table of groups.
- Sort avoidance
- Reading rows in index order so ORDER BY or GROUP BY needs no sort.
- Spill
- A sort or hash exceeding work_mem and writing to temporary files.
- Approximate distinct
- HyperLogLog-style counts such as APPROX_COUNT_DISTINCT, with about 1–2% error.
Visual diagram
Theory & example queries
Avoiding sorts and reducing rows
If an index matches the ORDER BY, the plan reads rows in order and stops at the LIMIT: ORDER BY created_at DESC LIMIT 20 with an index on created_at reads 20 entries instead of sorting millions. The same applies to GROUP BY: an index on the grouping columns lets a GroupAggregate stream through rows in order. PostgreSQL 13+ can also do an incremental sort when the input is already sorted by a leading column.
Otherwise, reduce the rows reaching the sort. Filter early, aggregate a fact table to the grouping key before joining dimensions for names, and replace SELECT DISTINCT after a join with EXISTS when you only need rows from one side. DISTINCT on many columns is a common sign of a fan-out somewhere upstream; fixing the join is faster and more correct than deduplicating afterwards.
| id | order_id | product_id | qty | price |
|---|---|---|---|---|
| 1 | 101 | 42 | 2 | 49.5 |
| 2 | 101 | 84 | 1 | 150 |
| 3 | 102 | 42 | 1 | 49.5 |
| id | name | price | category | stock |
|---|---|---|---|---|
| 42 | SQL Notebook | 49.5 | books | 18 |
| 84 | Mechanical Keyboard | 150 | hardware | 5 |
| 11 | Query Mug | 12.99 | gifts | 33 |
SELECT p.name, s.unitsFROM ( SELECT product_id, SUM(quantity) AS units FROM order_items WHERE created_at >= '2026-11-01' GROUP BY product_id ) s JOIN products p ON p.id = s.product_idORDER BY s.units DESCLIMIT 50;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Representative top products3 sample rows
| name | units |
|---|---|
| Wireless Mouse | 1840 |
| USB-C Cable | 1512 |
| Notebook | 980 |
Note: Sample totals are illustrative for the selected date range. The actual row count is capped at 50 and ordered by aggregated units descending.
groups millions of narrow rows, then joins only the product totals.
Key takeaway: Index order removes sorts; EXISTS and pre-aggregation remove rows.
Memory, spills and approximate counts
When a Sort or HashAggregate needs more than work_mem, it spills to disk (Sort Method: external merge Disk: … or batches in a hash). For a known heavy report, raise it for that session or transaction only, such as SET LOCAL work_mem = '256MB', rather than globally, since every sort in every connection can use that much. Selecting fewer and narrower columns also shrinks what each row costs to sort.
COUNT(DISTINCT user_id) over billions of events is expensive everywhere because every distinct value must be remembered. If 1–2% error is acceptable, approximate functions are far cheaper: APPROX_COUNT_DISTINCT in BigQuery, Snowflake and SQL Server 2019+, or the hll extension in PostgreSQL. For repeated dashboards, precompute daily distinct sets or counts in a summary table.
| id | order_id | product_id | qty | price |
|---|---|---|---|---|
| 1 | 101 | 42 | 2 | 49.5 |
| 2 | 101 | 84 | 1 | 150 |
| 3 | 102 | 42 | 1 | 49.5 |
BEGIN;SET LOCAL work_mem = '256MB';SELECT customer_id, COUNT(DISTINCT product_id)FROM order_itemsGROUP BY customer_id;COMMIT;PostgreSQL is the lesson baseline unless noted otherwise.
Open a transaction so changes can be checked and committed or rolled back together.
Representative distinct-product counts3 sample rows
| customer_id | count |
|---|---|
| 7 | 12 |
| 8 | 5 |
| 9 | 23 |
Note: The sample counts are illustrative. The surrounding PostgreSQL responses are BEGIN, SET and COMMIT; the larger work_mem applies only inside this transaction and is not a guarantee of a particular runtime.
The setting reverts at the end of the transaction.
Key takeaway: SET LOCAL work_mem for heavy jobs; approximate or precompute distinct counts.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Find the expensive node
Look for Sort, HashAggregate, Unique or GroupAggregate nodes with high time, many input rows or disk usage.
Sort Method: external merge Disk: 186MB
When to use it & trade-offs
What it is
GROUP BY, DISTINCT and ORDER BY all need rows brought together by value, which means a sort or a hash table. They get slow when there are many rows to sort, when the sort or hash spills past work_mem to disk, or when a join multiplies rows before deduplication. The fixes: read rows already in order from an index, reduce rows before grouping, aggregate before joining, raise work_mem for big jobs, and use approximate distinct counts where exact ones aren't needed.
Why it matters: Reports and dashboards are mostly GROUP BY and COUNT(DISTINCT), and APIs are full of ORDER BY … LIMIT. When they're slow, adding indexes at random rarely helps; knowing which plan node is the problem (Sort, HashAggregate, Unique) and why it's expensive leads straight to the fix.
When to reach for it
- Slow reports with DISTINCT or COUNT(DISTINCT)
- API pages using ORDER BY … LIMIT
- Sorts that spill to disk
When to avoid or be careful
- SELECT DISTINCT to hide duplicate rows from a join
- Raising work_mem globally to fix one query
- Exact distinct counts over billions of rows on every dashboard load
Ways to speed up grouping and sorting
Strengths: Often the biggest win; also fixes fan-out bugs.
Watch out: Requires rewriting the query.
Strengths: Removes the sort completely.
Watch out: Only helps queries matching the index order.
Strengths: No query change; approximation is orders of magnitude cheaper.
Watch out: Memory risk if set globally; approximate results.
Interview signals & numbers to know
When this topic comes up
- “This DISTINCT query takes 40 seconds”
- “Sort spills to disk”
- “Count unique users per day is slow”
- ORDER BY LIMIT performance
- HashAggregate vs Sort
Benchmarks & rules of thumb
- work_mem
- per sort or hash, per connection
- ~1–2%
- typical approximate distinct error
- PostgreSQL 13
- incremental sort
Common mistakes & follow-ups
Common interview mistakes
- Setting work_mem to 1GB globally, then running out of memory when 100 connections sort at once.
- Adding DISTINCT to a query whose join multiplies rows, making it slower and hiding the real bug.
- Relying on an index on created_at for WHERE status = 'refunded' ORDER BY created_at DESC LIMIT 20 when refunds are rare, so the backward scan reads millions of entries to find 20; an index on (status, created_at) fixes it.
Likely interviewer follow-ups
- How would you speed up SELECT DISTINCT over a large join?
- What does Sort Method: external merge mean, and how do you fix it?
- When would you use an approximate distinct count?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Optimizing Slow GROUP BY, DISTINCT & ORDER BY Operations with hands-on SQL practice and interview Q&A.