Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 135/ 160
07. Indexing, Query Optimization & Performance Tuning

Optimizing Slow GROUP BY, DISTINCT & ORDER BY Operations

Speed up sorts, distincts, and groups with indexes and rewrite tricks.

AdvancedSort Avoidance · DISTINCT3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

Aggregate first, then join for namesQuery example
1Input dataStart from the source rows or state that the statement sees.
order_items
3 rows
order_items sample rows
idorder_idproduct_idqtyprice
110142249.5
2101841150
310242149.5
products
3 rows
products sample rows
idnamepricecategorystock
42SQL Notebook49.5books18
84Mechanical Keyboard150hardware5
11Query Mug12.99gifts33
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  p.name,3  s.units4FROM5  (6    SELECT7      product_id,8      SUM(quantity) AS units9    FROM10      order_items11    WHERE12      created_at >= '2026-11-01'13    GROUP BY14      product_id15  ) s16  JOIN products p ON p.id = s.product_id17ORDER BY18  s.units DESC19LIMIT20  50;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/20
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative top products3 sample rows
Representative top products
nameunits
Wireless Mouse1840
USB-C Cable1512
Notebook980

Note: Sample totals are illustrative for the selected date range. The actual row count is capped at 50 and ordered by aggregated units descending.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

More memory for one reportQuery example
1Input dataStart from the source rows or state that the statement sees.
order_items
3 rows
order_items sample rows
idorder_idproduct_idqtyprice
110142249.5
2101841150
310242149.5
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1BEGIN;23SET4  LOCAL work_mem = '256MB';56SELECT7  customer_id,8  COUNT(DISTINCT product_id)9FROM10  order_items11GROUP BY12  customer_id;1314COMMIT;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Start transaction

Open a transaction so changes can be checked and committed or rolled back together.

1/14
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative distinct-product counts3 sample rows
Representative distinct-product counts
customer_idcount
712
85
923

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.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

The setting reverts at the end of the transaction.

Key takeaway: SET LOCAL work_mem for heavy jobs; approximate or precompute distinct counts.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1EXPLAIN

Find the expensive node

Look for Sort, HashAggregate, Unique or GroupAggregate nodes with high time, many input rows or disk usage.

Focus at this step

Sort Method: external merge Disk: 186MB

What to watch at this step
Input rows
the key number
Tip: use ← → to move between steps

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

Reduce rows (EXISTS, filter early, aggregate first)
Best for: DISTINCT after joins and large reports

Strengths: Often the biggest win; also fixes fan-out bugs.

Watch out: Requires rewriting the query.

Index that provides order
Best for: ORDER BY … LIMIT and grouping on indexed keys

Strengths: Removes the sort completely.

Watch out: Only helps queries matching the index order.

More work_mem or approximate counts
Best for: Big one-off sorts; huge distinct counts

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?
Interview tip: Always ask how many rows reach the sort before suggesting indexes or memory. Shrinking the input is the fix most candidates forget.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
Common Anti-Patterns That Break Indexes (Functions on Columns, Implicit Casts, Leading %)
Next topic
Keyset / Cursor Pagination vs Slow OFFSET Pagination