Query Optimization

SQL says what result you want; the query planner decides how to compute it. Optimization is the craft of reading the planner's decisions, finding where time is actually spent, and changing the query, the indexes or the statistics so the planner can choose better. This lesson teaches a repeatable tuning workflow using PostgreSQL's EXPLAIN. For Oracle-specific tuning (hints, DBMS_XPLAN, bulk PL/SQL), see the PL/SQL lesson Optimize.

How the Planner Works

For each statement, a cost-based planner enumerates possible execution plans — which index to use, in which order to join tables, which join algorithm to apply — estimates the cost of each from table statistics, and runs the cheapest. A slow query is usually one where the planner had a poor choice of options, or had wrong information about the data.

Statistics Drive Estimates

The planner's estimates come from statistics gathered by ANALYZE: row counts, the most common values, histograms of value distribution, and the fraction of nulls. Autovacuum runs ANALYZE automatically after enough changes, but statistics can lag after a bulk load or a sudden shift in data. When estimated and actual row counts diverge widely, refresh statistics first:

-- Refresh statistics for one table after a bulk load.
ANALYZE customer_order;

-- Collect a more detailed histogram for a skewed column.
ALTER TABLE customer_order ALTER COLUMN status SET STATISTICS 1000;
ANALYZE customer_order (status);

Common Plan Nodes

NodeWhat it doesTypical when
Seq ScanReads the whole table.Small tables, or a large share of rows is needed.
Index ScanWalks an index, fetching each matching row from the table.Selective conditions.
Index Only ScanAnswers from the index without visiting the table.A covering index exists.
Bitmap Heap ScanCollects matching row locations from indexes, then reads table pages in order.Moderately selective conditions, or several indexes combined.
Nested LoopFor each outer row, looks up matching inner rows.Few outer rows and an indexed inner side.
Hash JoinBuilds a hash table from one input, probes it with the other.Large unsorted inputs joined on equality.
Merge JoinMerges two inputs already sorted on the join key.Both sides sorted or indexed on the key.

Reading Execution Plans

EXPLAIN shows the chosen plan and its estimates. EXPLAIN ANALYZE actually runs the statement and adds real timings and row counts — so wrap data-changing statements in a transaction you roll back.

EXPLAIN ANALYZE

EXPLAIN (ANALYZE, BUFFERS)
SELECT c.full_name, count(*) AS orders
  FROM customer       AS c
  JOIN customer_order AS o ON o.customer_id = c.id
 WHERE o.ordered_at >= now() - interval '30 days'
 GROUP BY c.full_name;

A plan is a tree read from the most indented line outward: leaves read data, parents combine it. A shortened plan might look like this (illustrative numbers; yours will differ):

HashAggregate  (cost=4210.6..4310.6 rows=10000 width=40) (actual time=61.2..63.0 rows=8231 loops=1)
  ->  Hash Join  (cost=330.0..4085.6 rows=25000 width=32) (actual time=4.1..52.7 rows=24711 loops=1)
        Hash Cond: (o.customer_id = c.id)
        ->  Seq Scan on customer_order o  (cost=0.0..3690.0 rows=25000 width=8) (actual time=0.0..38.9 rows=24711 loops=1)
              Filter: (ordered_at >= (now() - '30 days'::interval))
              Rows Removed by Filter: 175289
        ->  Hash  (cost=205.0..205.0 rows=10000 width=40) (actual time=4.0..4.0 rows=10000 loops=1)
              ->  Seq Scan on customer c  (cost=0.0..205.0 rows=10000 width=40) (actual time=0.0..1.9 rows=10000 loops=1)
Planning Time: 0.4 ms
Execution Time: 63.8 ms

What to Look For

  • Where the time goes. actual time is cumulative for a node and its children; find the node whose own time dominates. Multiply by loops for nodes executed repeatedly.
  • Estimate vs reality. Compare rows= in the estimate with the actual rows. A mismatch of 10× or more often explains a bad join choice; check statistics and correlated predicates.
  • Rows removed by filter. Reading 200,000 rows to keep 25,000 suggests an index or a partial index on the filter column (here, ordered_at).
  • Buffers. With BUFFERS, shared hit pages came from memory and read pages from disk; high reads point to I/O, not CPU, as the bottleneck.
  • Spills. Sorts or hashes that report using disk need more work_mem or fewer rows.

Visual tools such as explain.dalibo.com render plans as trees and highlight the expensive nodes; avoid pasting plans that reveal sensitive table or literal values into public tools.

Finding the Queries Worth Tuning

Tune what matters to users and to the server. A query that takes 2 seconds once a day matters less than one that takes 20 milliseconds but runs 50,000 times an hour.

Rank Queries by Total Time

The pg_stat_statements extension aggregates statistics for every normalized statement. It must be listed in shared_preload_libraries (a restart is required) and then created in the database:

CREATE EXTENSION IF NOT EXISTS pg_stat_statements;

-- Top ten statements by total execution time (PostgreSQL 13+ column names).
SELECT round(total_exec_time::numeric, 0) AS total_ms,
       calls,
       round(mean_exec_time::numeric, 2)  AS mean_ms,
       rows,
       left(query, 80)                    AS query
  FROM pg_stat_statements
 ORDER BY total_exec_time DESC
 LIMIT 10;

The log_min_duration_statement setting complements it by logging every statement slower than a threshold, together with its parameters, and the auto_explain module can log the plans of slow statements automatically.

Spot Application-Level Problems

Some of the most expensive patterns are invisible in a single plan. The N+1 query problem — one query for a list, then one more query per item — shows up in pg_stat_statements as a cheap statement with an enormous calls count; fix it with a join or a single WHERE id = ANY(...) query. Fetching thousands of rows to display twenty, or columns that are never read, wastes I/O and network time no index can recover.

Tuning Techniques

Change one thing at a time and measure again. Most fixes fall into a small number of categories.

Write Index-Friendly Predicates

A predicate can use an index only if the indexed column appears unmodified — such predicates are called sargable. Wrapping the column in a function or arithmetic hides it from the index:

-- Not sargable: the function is applied to every row's column value.
SELECT id FROM customer_order WHERE date_trunc('day', ordered_at) = DATE '2026-11-01';

-- Sargable: the column stands alone; the range is computed once.
SELECT id FROM customer_order
 WHERE ordered_at >= TIMESTAMPTZ '2026-11-01'
   AND ordered_at <  TIMESTAMPTZ '2026-11-02';

The same applies to implicit type conversions (comparing a text column with a number), leading wildcards (LIKE '%abc'), and OR across different columns, which may be rewritten as a UNION ALL of two indexed queries.

Reduce the Work

  • Filter early and select only the needed columns, which may enable index-only scans.
  • Use keyset pagination (WHERE id > :last_seen ORDER BY id LIMIT 50) instead of large OFFSET values, which still read and discard every skipped row.
  • Replace correlated subqueries that run once per row with joins or EXISTS.
  • Precompute expensive aggregates in a materialized view or summary table when results may be slightly stale.

Tune Configuration Last

Server settings such as shared_buffers, work_mem, effective_cache_size and random_page_cost influence every query, which makes them powerful and risky. Set sensible baselines for the hardware (tools like PGTune give a starting point), then change them only with evidence. Raising work_mem globally to fix one report can exhaust memory when many sessions sort at once; set it per session or per role for the workload that needs it.

A Repeatable Tuning Workflow

Tuning by intuition produces indexes nobody can explain a year later. Follow the same six steps every time, in two phases.

Diagnose

  1. Define the target. “The order history page responds in under 200 ms at the 95th percentile” — not “make it faster”.
  2. Measure. Find the statements behind the slow path in pg_stat_statements or the slow-query log.
  3. Reproduce. Run EXPLAIN (ANALYZE, BUFFERS) with realistic parameters on production-like data volumes; plans on a tiny development database are meaningless.

Change and Verify

  1. Hypothesize and change one thing: statistics, an index, a rewrite, or a setting.
  2. Verify the improvement, and check that writes and other queries did not get slower.
  3. Record the before and after plans with the change, so the next person knows why the index exists.

Practice Lab

Use the million-row orders table from the Indexing lab, with pg_stat_statements enabled.

Read and Fix Plans

  1. Write a report query joining customers and orders for the last 30 days, and capture its EXPLAIN (ANALYZE, BUFFERS).
  2. Identify the node where most time is spent and whether estimates match actual rows.
  3. Make one change, rerun, and write two sentences explaining why the plan changed.

Tune a Workload

  1. Run a script that issues an N+1 pattern (one query per customer) and a non-sargable date filter for a few minutes.
  2. Find both problems from pg_stat_statements alone, without reading the script.
  3. Fix them, reset the statistics with SELECT pg_stat_statements_reset();, rerun, and compare total time.