Video in progress
What do you look at first in EXPLAIN (ANALYZE, BUFFERS) output?
First I compare the estimated rows= with the actual rows: a big gap is the cause of a bad plan. Then I look at loops, the node that took the most time, the ratio of read (from disk) to hit (from cache) in Buffers, and Rows Removed by Filter.
📖 Answer
Nested Loop (cost=0.85..1250.40 rows=12 width=64) (actual time=0.05..842.10 rows=48210 loops=1)
Buffers: shared hit=1200 read=96000
-> Index Scan using idx_user_city on app_user u (rows=3) (actual rows=4021 loops=1)
Index Cond: (city = 'Toshkent')
-> Index Scan using idx_order_user on orders o (rows=4) (actual rows=12 loops=4021)
Here is what I read from this fragment:
- the estimate error. The planner expected 3 users and there were actually 4021. That's why it chose a nested loop: right for 3, bad for 4021. The cause is often stale statistics or correlated columns.
- loops. The
actual timeandrowsof the inner node are for a single loop. The real total isrows × loops. - Buffers.
read=96000is 96 thousand pages (about 750 MB) from disk. If you run it a second time it turns intohit, so tell "cold" and "warm" measurements apart. - if Rows Removed by Filter is large, the index doesn't fully match the condition.
Sort Method: external merge Diskmeanswork_memwasn't enough.
Be careful: EXPLAIN ANALYZE really executes the query. For a DELETE or UPDATE, run it inside BEGIN; ... ROLLBACK;.
Sign up to mark studied questions and save your progress.