AI Hints
Home›PostgreSQL Tutorial›Finding and Fixing Slow Queries
PostgreSQL · Lesson 92 of 120

A Slow Query Workflow

Measure, explain, fix.

⏱ 2 min read▶ Video at 1:22:55🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

A slow page. Where do you start? Follow the same steps every time. Find the query, explain it, fix the biggest problem, and measure again.

  • Find
  • Explain
  • Fix
  • Measure

The workflow

Find the slow query with pg stat statements. Run explain analyze on it. Look for the slowest step, and big gaps in row estimates. Fix one thing, like adding an index or rewriting the query. Then measure again.

  1. Findtop queries
  2. ExplainEXPLAIN ANALYZE
  3. Diagnoseslow node, bad estimates
  4. Fixindex, rewrite
  5. Measureagain

Fix: index a foreign key

Postgres doesn't index foreign key columns automatically. Order items by book ID does a full scan. One index fixes it. Run it. A scan of every row, then a quick index lookup.

query.sqlsql
EXPLAIN (COSTS OFF) SELECT * FROM order_items WHERE book_id = 9;

CREATE INDEX ON order_items (book_id);
ANALYZE order_items;

EXPLAIN (COSTS OFF) SELECT * FROM order_items WHERE book_id = 9;
Output
       QUERY PLAN
-------------------------
 Seq Scan on order_items
   Filter: (book_id = 9)
(2 rows)

CREATE INDEX
ANALYZE
                     QUERY PLAN
----------------------------------------------------
 Bitmap Heap Scan on order_items
   Recheck Cond: (book_id = 9)
   ->  Bitmap Index Scan on order_items_book_id_idx
         Index Cond: (book_id = 9)
(4 rows)

Summary

Find, explain, fix one thing, and measure again. And remember to index foreign keys. Next, basic configuration.

Key takeaways
  • Find
  • Explain
  • Fix
  • Measure
Next up: Configuration Basics — the settings that matter