Boss lesson · Unit 02
Fix the slow query
Read a plan, pick the index, confirm the fix
What you practise
- Read a query plan (
EXPLAIN QUERY PLANhere,EXPLAIN ANALYZEin Postgres): scan vs search, choose the index, confirm the plan changed, the N+1 query problem
Try a question from this lesson
Pick one
A dashboard runs SELECT * FROM orders WHERE user_id = 42 and takes 4 seconds. The table has 10,000,000 rows; user 42 has 12. Most likely cause?
Correct answer
It reads all 10,000,000 rows to find the 12
Why
Twelve rows are nothing. Reading ten million to find them is the 4 seconds. That is a guess, though, and this lesson is about not guessing: ask the database what it does.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Reading a plan
Every database can explain itself. SQLite prints SCAN or SEARCH. Postgres prints Seq Scan (read everything) or Index Scan.
In Postgres, EXPLAIN shows the plan with estimated costs. EXPLAIN ANALYZE also runs the query and reports real times and row counts, like the ten million rows thrown away here.
Seq Scan on orders
Filter: (user_id = 42)
Rows Removed by Filter: 999998810 more exercises in the app
- 3× type the answer
- 2× fill the blanks
- 3× multiple choice
- 1× true or false
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.