SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
  • Indexing
  • Partitioning
  • Replication
  • Sharding
  • Query Optimization
  • Denormalization
  • Materialized Views
  • Connection Pooling
  • Replication Models
  • Replication Lag
  • Quorum (R + W > N)
  • Shard Keys, Hot Shards and Resharding
  • Cross-Shard Joins
  • Backups, RPO, RTO and Disaster Recovery
  • Point-in-Time Recovery
  • Data Archiving and TTL
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Data and Storage/Database Scaling

Query Optimization

Make slow queries fast: read the plan, add the right index, fetch less.

⏱ 14 min readIntermediateInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Query optimization means making a database query use less work: fewer rows read, less data sent, fewer round trips. The result is the same answer, much faster.

  • First measure: find the slow queries, then read the query plan (the database's own explanation of how it will run the query).
  • The biggest wins are usually the right index, fetching less (fewer columns and rows), and fewer queries (no N+1).
  • Never guess. Change one thing, measure again.

02Concept: What is it?

You write SQL that says what you want. The database decides how to get it. A part called the query planner (or optimizer) picks a plan. It guesses the cost of each possible plan, using statistics about your tables, and runs the cheapest. Most of the time this works. When it does not, queries get slow.

What happens to a query
📝SQLwhat you want
→↓parse
🧠Plannerpicks the cheapest way
→↓plan
⚙️Executorreads indexes and tables
→↓rows
📦Result
The planner turns SQL into a plan. EXPLAIN shows you that plan.

A plan is a tree of steps. The most important question for each step is: how many rows does it touch? A step that reads a million rows to return ten is the problem.

🧠Scan vs seek
A full table scan (also called a sequential scan) reads every row. An index seek jumps straight to the matching rows, like using the index at the back of a book. On a small table, a scan is fine. On a big one, it is the usual cause of slowness.

03Real-Life Example

🍵Finding a Book in a Library
You need all books by one author. Without a catalogue, you walk every shelf and check every spine. That is a full scan. With a catalogue sorted by author, you look up the name and go to the exact shelf. That is an index. Now suppose you only need the titles. Do not carry all the books home (fetch fewer columns). Only need the first 20? Stop after 20 (LIMIT). And do not walk to the library 21 times for 21 small questions when one trip would do (N+1).
Library
Query
Checking every spine
Full table scan
Looking in the author catalogue
Index lookup
Carrying home whole books
SELECT * (all columns)
Writing down only titles
Select only the needed columns
Stopping after 20 books
LIMIT
Twenty trips for twenty questions
The N+1 query problem
One trip, one list
A JOIN or a batched IN query
A librarian who knows the shelves are changing
Up-to-date table statistics
Before and after
Before
🐌Seq Scan1,000,000 rows read
📦SELECT *2 KB per row
🔁N+121 queries
After
⚡Index Scan20 rows read
🪶3 columns60 bytes per row
🧩1 join1 query
Same answer. The fixed version touches a tiny part of the data.

04Why Do We Need It?

⚡Faster pages
A query that takes 2 seconds makes the whole page take 2 seconds.
💸Lower cost
Less CPU and I/O means a smaller database bill, or a longer life for the one you have.
📈More traffic on the same box
Fast queries free up connections and CPU for other users.
🧯Avoid outages
One slow query can hold locks, fill the connection pool and take everything down.
🧪Cheaper than sharding
Fixing queries is the cheapest way to scale. Do it before bigger changes.
😀Happier users
Speed is a feature that people notice.
The fastest query is the one that touches the least data. Make the database do less, not more.

05Where Do We Use It?

🔎Search and filter pages
Filters like status, date or owner need matching indexes.
📊Dashboards and reports
Big GROUP BY queries. Often solved with summaries or materialized views.
🧾List and feed pages
Newest-first lists with paging. Index the sort order and avoid deep OFFSET.
🧑‍💻ORMs and APIs
Hidden N+1 queries and SELECT * come from convenient code.
🔁Background jobs
Big batch updates that lock rows or scan whole tables.
🛠️Incident work
When the database is on fire, the slow query log is the first place to look.

06Types / Parts / How It Works

The main levers

LeverWhat you doWhy it helps
Add the right indexIndex the columns used in WHERE, JOIN, ORDER BY. A composite index follows the order: equality columns first, then range or sort.Turns a scan into a seek, and can remove the sort step.
Select fewer columnsName the columns. Avoid SELECT *.Less data to read, send and parse. May allow an index-only scan (a covering index).
Limit the rowsAdd LIMIT. Use keyset paging (WHERE id > last_seen) instead of big OFFSET.The database can stop early. OFFSET 100000 still reads and drops 100000 rows.
Fix N+1Use a JOIN, or one IN (...) query, or batching.Removes many network round trips.
Keep filters index-friendlyAvoid functions on indexed columns (WHERE LOWER(email) = ...) and leading wildcards (LIKE '%abc').Otherwise the index cannot be used.
Update statisticsRun ANALYZE (or your engine's equivalent).The planner picks plans from stats. Old stats lead to bad plans.
Rewrite the queryReplace correlated subqueries with joins, use EXISTS instead of IN on big sets, filter early.Gives the planner a cheaper path.
Cache or precomputeCache the result, or store it in a summary table or materialized view.Avoids running the heavy query at all.
Reading a plan, top to bottom
📦Limit20 rows
↑
🔀Sortcost 8,400 rows 50,000
↑
🐌Seq Scan on postscost 18,000 rows 1,000,000
The bottleneck Possible extra work Cheap
Find the most expensive node. Ask how many rows it touches, and whether an index would help.
Typical workflow (PostgreSQL style, other engines are similar)
EXPLAIN ANALYZE
SELECT id, title, created_at
FROM posts
WHERE author_id = 42
ORDER BY created_at DESC
LIMIT 20;

-- Fix: one composite index serves both the filter and the sort
CREATE INDEX posts_author_created ON posts (author_id, created_at DESC);
EXPLAIN
estimated plan
  • Does not run the query
  • Shows the planned steps and estimated rows
  • Safe to run on production
EXPLAIN ANALYZE
actual run
  • Actually runs the query
  • Shows real time and real row counts
  • Careful with INSERT, UPDATE and DELETE
VisualizerFix a slow query with togglesGrow the table to 10M rows, then turn the fixes on one by one. Which one changes the plan the most? Which one fixes the number of queries?
Apply fixes (toggle any mix)
The query
SELECT *
FROM posts p
WHERE p.author_id = 42
ORDER BY p.created_at DESC
;
Simplified query plan (bar = share of the heaviest step)
Seq Scan on posts (read every row)500 ms
check all 1M rows against author_id
Sort by created_at2 ms
sort 1k matching rows
Return all columns (SELECT *)16 ms
1k rows x 2000 bytes = 2000 KB over the network
Repeat 20 times for the author names (N+1)36 ms
one extra query per post, each with its own network trip
Total time compared with the slow baseline556 ms
Queries sent
21
N+1 pattern
Rows read (main query)
1M
Estimated time
556 ms
Speed-up
1.0x
Slow baseline: 21 queries, and the main one reads every one of 1M rows. Estimated 556 ms. Turn on the fixes one by one.

A simplified cost model with made-up but sensible constants (deterministic, no timing of real databases). Real plans from EXPLAIN look different and depend on your data, statistics and engine. The lesson is the order of impact: avoid reading rows you do not need, then avoid sending data you do not need, then avoid extra round trips.

07How to Use It / Steps / Implementation

A calm way to tune a query

  1. 1
    Find the slow queries
    Use the slow query log, pg_stat_statements (PostgreSQL), the performance schema (MySQL), or your APM tool. Sort by total time, not only by slowest single run.
  2. 2
    Reproduce with real-sized data
    A query that is fast on 1,000 rows may be awful on 10 million.
  3. 3
    Read the plan
    Run EXPLAIN (ANALYZE). Look for sequential scans on big tables, big sorts, estimates far from actual rows, and nested loops over many rows.
  4. 4
    Try the cheapest fix first
    A missing index, SELECT *, a missing LIMIT, or an N+1 loop in the app.
  5. 5
    Change one thing
    Then measure again. Compare time and rows touched.
  6. 6
    Check the write cost
    Every index slows inserts and updates and uses space. Add only what you need.
  7. 7
    Protect the win
    Add a query test or alert so the same slow query does not return after a refactor.
⚠️Do not guess
An index the planner never uses is pure cost. A query that was fast last month can turn slow as the table grows or the statistics change. Always look at the plan with realistic data.
Order of impact (rough)touch fewer rows, then send fewer bytes, then make fewer trips

08Key Terms to Know

TermMeaning in easy words
Query planner / optimizerThe part of the database that chooses how to run a query
Query planThe chosen list of steps, shown by EXPLAIN
Full table scanReading every row of a table
Index seek / scanUsing an index to find matching rows quickly
Covering indexAn index that holds all the columns the query needs, so the table is not read
SelectivityHow small a share of rows a filter keeps. A highly selective filter keeps few rows.
Cardinality estimateThe planner's guess of how many rows a step returns
StatisticsSummaries of the data (counts, value spread) that the planner uses
N+1 problemOne query for a list, then one more query for each item
Keyset (seek) paginationPaging with WHERE id > last_seen instead of OFFSET
Slow query logA log of queries that took longer than a set time

09Pros, Cons and Trade-offs

✅ Pros
  • Huge speed-ups, often 10x to 1000x
  • Cheap compared with new hardware or sharding
  • Frees CPU, memory and connections
  • Makes the app feel faster
  • Builds understanding of your data
⚠️ Cons
  • Needs measurement and real-sized data
  • Indexes slow writes and use space
  • Plans change as data and statistics change
  • Easy to over-optimize rarely used queries
  • Engine-specific details (hints, plan shapes)

Trade-offs

ChoiceWe gainWe lose
More indexesFaster readsSlower writes, more disk and memory
Covering indexNo table lookupsA bigger index to maintain
Denormalize or precomputeSkip joins and heavy workStale or duplicated data
Cache the resultNo query at all on a hitInvalidation and stale data
Query hintsForce a known good planFragile when data changes
Bigger LIMIT, bigger pagesFewer round tripsMore data per request

10Common Problems and Mistakes

Common mistakes

  1. SELECT * everywhere. It moves columns you never use, and blocks index-only scans.
  2. The N+1 loop. A list page that runs one extra query for every row. ORMs hide this well.
  3. A function on the indexed column. WHERE DATE(created_at) = ... cannot use an index on created_at. Use a range instead.
  4. Deep OFFSET paging. Page 5,000 has to skip 100,000 rows each time.
  5. Wrong column order in a composite index. An index on (created_at, author_id) does not help a filter on author_id.
  6. Indexing everything. Writes crawl and the planner has too many choices.
  7. Trusting a fast dev database. Production data is bigger and more skewed.

Things to watch

📉Stale statistics
After a big load or delete, run ANALYZE so estimates are right.
🔒Long transactions and locks
A slow update can block others even if reads are fast.
🧮Bad estimates
If estimated rows and actual rows differ by 100x, the planner may choose the wrong plan.
🎯Parameter sniffing
A plan cached for one parameter value may be bad for another (SQL Server and others).

11Real-World Examples

🐘PostgreSQL
EXPLAIN (ANALYZE, BUFFERS), pg_stat_statements and auto-vacuum with auto-analyze are the usual toolbox.
🐬MySQL
EXPLAIN, EXPLAIN ANALYZE in newer versions, the slow query log and the performance schema.
🪟SQL Server
Execution plans in the UI and Query Store to track plan changes over time.
🍃MongoDB
explain() shows whether a query used an index (IXSCAN) or scanned the collection (COLLSCAN).
🧰ORMs
Rails, Django, Hibernate and others offer eager loading to avoid N+1 queries.
☁️Cloud tools
Managed databases offer performance dashboards and index advisers (general idea).
📝Note
These are general ideas. Plan formats and commands differ between engines and versions.
Mini case: a slow orders page
🐢Slow page3.2 s
→↓slow log
🔍EXPLAINSeq Scan on orders
→↓index (customer_id, created_at)
🧩Fix N+1eager load items
→↓re-measure
🚀Fast page90 ms
Measure, read the plan, fix the biggest cost, measure again.

12Related Topics to Read Next

Indexing→

The single biggest lever for faster queries.

B-Trees and B+ Trees→

The structure behind most indexes.

Denormalization→

Avoid costly joins by storing data together.

Materialized Views→

Precompute heavy queries.

Connection Pooling→

Slow queries also hold connections.

What is Caching?→

Skip the query when you can.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔What: make the database touch fewer rows, send less data, and make fewer trips.
  • ✔First: measure. Slow query log, then EXPLAIN (ANALYZE) on real-sized data.
  • ✔Biggest win: the right index, in the right column order.
  • ✔Fetch less: name columns (no SELECT *), use LIMIT, use keyset paging.
  • ✔Fewer queries: kill N+1 with a join, a batch, or eager loading.
  • ✔Index traps: functions on columns, leading wildcards, wrong order, stale statistics.
  • ✔Cost: every index slows writes. Add what you use.
  • ✔One line: “Read the plan, add the right index, and fetch only what you need.”
← Previous
Sharding
Next →
Denormalization