Query Plans, Indexes and Performance
Read EXPLAIN output, understand scans, joins and sorts, and use indexes, statistics and query rewrites to make slow SQL fast.
Advanced · about 8 hours · difficulty 4/5
Learn first: Window Functions
Two queries that return the same rows can differ by 1000x in runtime. Knowing how the engine executes SQL is what separates a data engineer from someone who just writes queries.
Reading a plan
EXPLAINshows the plan;EXPLAIN ANALYZEruns it and shows actual times and row counts.- Read from the innermost node outwards. Look for sequential scans on large tables, estimated vs actual rows that differ wildly, and expensive sorts or hash operations spilling to disk.
Join algorithms
- Nested loop: good when one side is tiny and the other is indexed.
- Hash join: builds a hash table on the smaller side; the workhorse for large joins.
- Merge join: both sides sorted on the key.
The same ideas reappear in Spark as broadcast and sort-merge joins.
Indexes in OLTP databases
- B-tree indexes speed up equality and range filters and joins on the indexed columns.
- Composite index column order matters (
(customer_id, created_at)helps "orders for a customer by date"). - Indexes slow down writes and use space; add them for real query patterns.
Warehouse performance is different
Columnar warehouses rarely use B-tree indexes. Instead you rely on partitioning, clustering or sort keys, pruning and selecting fewer columns. SELECT * on BigQuery costs money because you pay per byte scanned.
Pitfalls
- Wrapping an indexed column in a function (
WHERE DATE(created_at) = ...) so the index cannot be used. - Stale statistics causing bad plans; run
ANALYZE. - Optimising a query without measuring before and after.
You are ready to move on when you can take a slow query, read its EXPLAIN ANALYZE output, name the bottleneck and show a measured improvement after a rewrite or index.
Key concepts
- EXPLAIN and EXPLAIN ANALYZE
- Sequential vs index scans
- Nested loop, hash and merge joins
- B-tree and composite indexes
- Table statistics
- Sargable predicates: Filters that can use an index
- Partition pruning in warehouses
- Materialized views
Mini project
Generate a 10 million row orders table in PostgreSQL. Write five slow queries, capture EXPLAIN ANALYZE for each, fix them with indexes or rewrites, and publish a before and after table of runtimes in your repo.
Check yourself
A query filters WHERE DATE(created_at) = '2026-10-01' and ignores the index on created_at. Why, and how do you rewrite it?
Free resources
- PostgreSQL: Using EXPLAIN (PostgreSQL)
- PostgreSQL: Indexes (PostgreSQL)
- Use The Index, Luke (Markus Winand)