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 time and rows of the inner node are for a single loop. The real total is rows × loops.
  • Buffers. read=96000 is 96 thousand pages (about 750 MB) from disk. If you run it a second time it turns into hit, 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 Disk means work_mem wasn't enough.

Be careful: EXPLAIN ANALYZE really executes the query. For a DELETE or UPDATE, run it inside BEGIN; ... ROLLBACK;.