skipnothing/SQL

Join Algorithms

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.

  • ▸Pick any of the three procedures and the same rows come back; only the engine's workload changes.
  • ▸A join-column index can speed one procedure, feed a second, and be ignored entirely by the third.
  • ▸No procedure wins everywhere; the planner prices all three on row counts and sort order, then picks.
BUILDS ON
01

One join, three algorithms

Three rows in users, five in orders, and an inner join on user_id that returns four matched pairs. That result is fixed: the same four rows, every time. But "return the matched pairs" is a description of the answer, not a recipe for finding it. The engine still has to decide, physically, how to hunt down which orders row pairs with which users row. There are three standard procedures for that hunt, and they are wildly different from each other. One re-reads a table over and over. One builds a lookup structure in memory. One marches down two sorted lists in step. Run any of the three and the four output rows are identical. What changes is how much work the engine does to produce them. The join you wrote names the rows; the procedure the engine runs names the cost.

ONE JOIN, THREE PROCEDURES, ONE RESULT

Keep going, sign up to unlock the rest

4 more parts in this topic, plus 30+ more topics in SQL.

Sign up, it's freeSee the full SQL