SQL query optimization: reading EXPLAIN ANALYZE and fixing the N+1 problem
Vinnie reads a query plan with EXPLAIN and EXPLAIN ANALYZE, comparing the planner's guesses with what really happened; then sniffs out the N+1 problem, where one list turns into a query per row, and fixes it with a join, a batch or eager loading. Plus: select only the columns you need.
Diagrams in this video · 1Free in archhy
The diagrams, full size
Copy any of them into archhy, free, and change it for your own system.
After this lesson you can
- Read a query plan with EXPLAIN and EXPLAIN ANALYZE
- Recognize the N+1 problem and fix it with a join, a batch or eager loading
- Select only the columns a query needs
Transcript
SQL query optimization: reading EXPLAIN ANALYZE and fixing the N+1 problem
Vinnie here. Rung two. Query optimization. Today, we check the database really uses our indexes, and catch a slow pattern hiding in almost every app.
Read the plan
First, read the plan. Explain shows the plan the database picked, with its estimated cost, in the planner's own units, not milliseconds. Explain analyze goes further. It actually runs the query, and adds the real times and row counts. Read it from the top. How did it get in? An index scan means an index is in play. A seq scan on a big table, when you wanted a few rows, is a sniff worth following. Then compare the guesses with reality. The planner expected five rows, and got six. Close enough. When estimates are wildly off, the planner can choose a bad plan. One warning. Because analyze really runs the statement, an update or delete really happens. Wrap it in begin, and roll back.
The N + 1 problem
Now the slow pattern. It's called N plus one, and it looks completely innocent in code. One. The app runs one query to fetch a list. Say, fifty orders. Two. Then it loops over them, and for each order, it asks for the customer. That's fifty more queries. Three. Fifty-one round trips. Each one is quick on its own, but each waits on the network. Make it a thousand orders, and the page crawls. Four. The first fix. A join. Ask for the orders and their customers in one query. Five. Or batch it. Fetch the orders, then fetch all their customers in a second query, where the ID is in that list. Two queries, not fifty-one.
Your ORM can do it for you
Most of the time, N plus one comes from an ORM, an object-relational mapper, loading related rows lazily, one at a time. So ask it to load them eagerly. In Rails, that's includes. In Django, select related does a join, and prefetch related does a batch. While you're there, select only the columns you need. Select star drags every column across the network, and it can stop a covering index from doing its job. And to find which queries to fix first, PostgreSQL's pg stat statements extension tracks how often each statement runs, and how long it takes.
The trade-off
Is there a catch? A little one. A join on a one-to-many relationship repeats the parent row for every child, so a big join can carry more data than you expect. That's when a batch is better. A batch with tens of thousands of IDs is its own problem. Split it into chunks. And don't spend a day tuning a query that runs once a day. Fix the ones that add up to the most time.
Reading plans, everywhere
Every big database can show you its plan. PostgreSQL has explain analyze, and buffers adds how many blocks it found in its cache, and how many it had to read. A managed PostgreSQL, on any cloud, reads the same. MySQL has explain analyze too, shown as a tree of steps. In SQL Server Management Studio, turn on include actual execution plan. And in MongoDB, explain with execution stats runs the winning plan, and reports what it did.
Remember
Let's recap. Don't guess. Read the plan, and compare the estimates with the actual rows. Kill N plus one with a join, a batch or eager loading. And select only the columns you need. My nose likes a tidy query.
The full article, and what's next
Next time, rung three. Connection pooling. Why opening a database connection costs more than you think. See you there.





