1 of 4

Your RightSignal

How databases work · 8 of 91 / 3

Query planning

The concept

Your SQL says what rows you want, never how to find them

SQL is declarative: you say what result you want, not how to get it. The query planner, or optimizer, lists the possible ways to answer a query and runs the one it expects to be cheapest.

For SELECT * FROM orders WHERE customer_id = 42, the database can read every row, or look up 42 in a B-tree index and fetch only the matches. Both give the same answer. Which is cheaper depends on how many rows match.

Joins multiply the choices. 3 tables can be joined in 3! = 6 orders, and each join can be a nested loop (look up matches row by row), a hash join (build and probe a hash table) or a merge join (walk two sorted lists).