skipnothing/SQL
UNIT 08

How Queries Run

Indexes, EXPLAIN, join algorithms, the antipatterns that kill performance

Up to now the database has been a black box. This unit opens it: indexes as data structures, the planner as a cost-based decision maker, join algorithms, and the antipatterns that turn fast queries slow.

Loading…
BUILDS ON
TOPICS
#28

Indexes

Trace how an index turns a full-table scan into a few-step lookup, judge when the engine skips it for a sequential scan, and apply the leftmost-prefix and covering-index rules to decide which columns to index.

An orders table holds a million rows. You ask for the ten that belong to one customer with WHERE user_id = 7, and the engine reads all million, row by row, checking each one, to hand back ten.

14 min
#29

EXPLAIN & the Planner

Read an EXPLAIN plan inside-out, decode each node's cost and row estimate, and use EXPLAIN ANALYZE to catch the bad row estimate behind a slow plan.

You indexed amount, ran SELECT * FROM orders WHERE amount > 0, and it is still slow. The engine decided how to run that query before it touched a row, and it will show you what it chose.

15 min
#30

Join Algorithms

Choose between nested loop, hash, and merge join by row count, index shape, and sort order, watch why each wins a different region, and predict which one the planner will price cheapest.

Four rows come back from a join of users and orders. The engine had three completely different procedures it could have run to find those same four rows, and it picked one by guessing which would be cheapest.

14 min
#31

Query Antipatterns

Spot the per-row loop that fires 1 + N queries, see why a leading wildcard or a function-wrapped column abandons an index, and rewrite each so the engine does only the work the result needs.

Two queries return the exact same rows from orders. One finishes in a single trip to the database; the other quietly fires a hundred and one, and the row counts on screen give you no hint which one you wrote.

13 min
All units