query planner · toy cost model

Join-Order Explainer

Four tables, one query, 24 possible join orders — all returning the identical answer. Pick the wrong one and the database touches hundreds of times more rows. Drag any slider; every plan is re-costed and re-ranked live.

The query joins are unordered

SELECT  r.name, p.name, count(*)
FROM    orders   o
JOIN    users    u ON o.user_id    = u.id
JOIN    products p ON o.product_id = p.id
JOIN    regions  r ON u.region_id  = r.id
GROUP BY 1, 2

SQL says what, never how. The planner may join these four tables in any sequence. This demo enumerates every left-deep order (join one table at a time into a growing intermediate result) and costs it as rows scanned.

Schema editable

Row countstype 2M, 1e6, 500000
Join selectivity x1 = one match per key

Selectivity s is the fraction of all row pairs that match, so |A ⋈ B| = |A| × |B| × s. At x1 it is 1 / distinct keys — a textbook foreign key. Slide up to model a duplicated or fuzzy key.

Selected plan click any order below

left-deep tree · read bottom-up
#join inonrows out

All 24 left-deep orders ranked by rows scanned

best keyed join cross product bar = log scale