skipnothing/SQL

EXPLAIN & the Planner

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.

  • ▸The plan's cost numbers are guesses in an arbitrary unit; the one worth checking is the estimated row count.
  • ▸The engine prices each candidate plan from its row estimates and runs the cheapest, even when that skips your index.
  • ▸Run the query for real and the true row count prints beside the guess; the gap is your slow plan.
BUILDS ON
01

The Plan, Read Inside-Out

Before the engine reads one row of orders, it decides how it will run your query: which structure to read, in what order, what to do with the results. Put EXPLAIN in front of the query and it hands that decision back to you instead of running it.

What comes back is not rows. It is a tree of steps, drawn top to bottom but read the other way. The most indented step is where the work starts; each step above consumes what the one below it produced, until the top step is the result you asked for. Read it inside-out and the engine's reasoning reads in the order it actually happens.

EXPLAIN RETURNS A TREE OF STEPS

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