Diagnose and improve SQL query performance

8 steps · about 4 h 15 min · Intermediate

  1. Read an execution plan (guide, PostgreSQL documentation, 40 min)

    Connect plan nodes, costs and row flow to the work PostgreSQL expects to perform.

  2. Measure with EXPLAIN ANALYZE safely (reference, PostgreSQL documentation, 30 min)

    Collect actual timing and row counts while remembering that the statement really executes.

  3. Match an index type to the predicate (guide, PostgreSQL documentation, 35 min)

    Choose B-tree, hash, GiST, SP-GiST, GIN or BRIN based on operators and data shape.

  4. Order a multicolumn index (reference, PostgreSQL documentation, 30 min)

    Align leading columns with the filters that can constrain the search effectively.

  5. Consider a partial index (reference, PostgreSQL documentation, 25 min)

    Index a stable useful subset when a full index would add unnecessary size and write cost.

  6. Understand planner statistics (guide, PostgreSQL documentation, 35 min)

    Relate poor row estimates to sampled distributions, distinct counts and column correlation.

  7. Refresh statistics deliberately (reference, PostgreSQL documentation, 25 min)

    Give the planner current evidence after meaningful data changes rather than changing settings blindly.

  8. Compare the plan after indexing (guide, PostgreSQL documentation, 35 min)

    Verify actual work, timing and maintenance tradeoffs before keeping the new index.