DatabasesVol. 4 · Part IV
0 / 0

Shelves / Databases

DB·60

Query Optimisation

Making queries fast on purpose. Covers how the optimiser decides (selectivity, cardinality, statistics and cost), scans (sequential, index, index-only, bitmap), join algorithms (nested loop, hash join, merge join), sorts and aggregation, designing composite, covering, partial and expression indexes, prepared statements and generic plans, the common anti-patterns, and a repeatable workflow from slow query to EXPLAIN ANALYZE to hypothesis, change and benchmark, with a worked example. PostgreSQL first, with MySQL, SQL Server and Oracle notes.

26 topics · ~23 min read · 30-question quiz
Updated Suggest a correction

Start here: why is this query slow?

The planner's job

SQL says what you want; the planner (or optimiser) decides how: which table to read first, whether to scan it or use an index, which join algorithm to use, whether to sort or hash. For a query joining five tables there are thousands of possible plans; the planner estimates the cost of the promising ones using its statistics (row counts, value distributions) and picks the cheapest. When queries are slow, it's almost always for one of three reasons: there's no good access path (a missing index), the planner's estimates are wrong, or the query is written in a way that prevents a good plan. EXPLAIN ANALYZE shows which.

Reading a plan

"Asha's last five orders" without a suitable index:

Text
EXPLAIN ANALYZE SELECT id, placed_at, total_paise FROM o2 WHERE customer_id = 4242 ORDER BY placed_at DESC LIMIT 5;

 Limit  (cost=41625.10..41625.68 rows=5 width=20) (actual time=80.880..82.109 rows=5 loops=1)
   ->  Gather Merge  (… rows=12 …) (actual … rows=5 loops=1)
         Workers Planned: 2
         ->  Sort  (… rows=6 …) (actual … rows=3 loops=3)
               Sort Key: placed_at DESC
               ->  Parallel Seq Scan on o2  (cost=0.00..40625.00 rows=6 width=20) (actual time=15.919..73.076 rows=5 loops=3)
                     Filter: (customer_id = 4242)
                     Rows Removed by Filter: 999995
 Execution Time: 82.162 ms

Read a plan from the innermost (most indented) node outwards: each node produces rows for its parent.

  • Parallel Seq Scan: three processes (2 workers plus the leader, loops=3) each read a third of the table, testing every row; Rows Removed by Filter: 999995 per process means 3 million rows read to find 15.
  • Sort, Gather Merge, Limit: sort each worker's matches, merge them, take five.
  • cost=… is the planner's estimate in arbitrary units (startup..total); rows=6 is its row estimate; actual … rows=5 is reality. Comparing estimated and actual rows is the most important habit in this chapter.
Text
CREATE INDEX o2_cust_placed ON o2 (customer_id, placed_at DESC);

 Limit  (cost=0.43..21.85 rows=5 width=20) (actual time=0.395..0.412 rows=5 loops=1)
   ->  Index Scan using o2_cust_placed on o2  (cost=0.43..64.69 rows=15 width=20) (actual … rows=5 loops=1)
         Index Cond: (customer_id = 4242)
 Execution Time: 0.648 ms

With an index on (customer_id, placed_at DESC), the planner walks to Asha's entries, which are already in the required order, reads five and stops: no sort, no scan, 127× faster. The column order matters: customer_id first (the equality), then placed_at (the order), as the lab measures.

Joins

Text
EXPLAIN ANALYZE SELECT c.city, count(*), sum(o.total_paise)
FROM o2 o JOIN c2 c ON c.id = o.customer_id WHERE o.placed_at >= '2026-06-01' GROUP BY c.city;

 Parallel Hash Join  (… rows=17145 …) (actual … rows=13920 loops=2)
   Hash Cond: (c.id = o.customer_id)
   ->  Parallel Seq Scan on c2 c  (… rows=100000 loops=2)
   ->  Parallel Hash
         ->  Parallel Seq Scan on o2 o  (… rows=13920 loops=2)
               Filter: (placed_at >= '2026-06-01 …')
               Rows Removed by Filter: 1486080
 Execution Time: 122.821 ms

CREATE INDEX o2_placed ON o2 (placed_at);
   ->  Parallel Index Scan using o2_placed on o2 o  (… rows=13920 loops=2)
         Index Cond: (placed_at >= '2026-06-01 …')
 Execution Time: 57.240 ms

PostgreSQL has three join algorithms. A nested loop looks up matches for each outer row (great when the outer side is small and the inner side is indexed). A hash join builds a hash table from one side and probes it with the other (good for large, unsorted inputs, as here). A merge join walks two sorted inputs in step. The planner chose a hash join; adding an index on placed_at replaced the scan of 3 million orders with an index range scan of the 28,000 recent ones, halving the time; what remains is reading all 200,000 customers to build the hash, which is cheap.

The workflow

  1. Find the queries that matter: pg_stat_statements ranks queries by total time (frequency × duration), which is usually different from "the slowest query".
  2. Explain with EXPLAIN (ANALYZE, BUFFERS) on realistic data, never on an empty dev database.
  3. Compare estimated and actual rows at each node; a large mismatch means the planner was misled (stale or missing statistics, correlated columns, functions on columns).
  4. Fix the cause: an index that matches the filter and order, rewriting the query so an index can be used, better statistics, or less work (fewer rows, fewer columns).
  5. Verify with the plan and the timing, and watch for regressions (extra indexes slow writes).

How deep to go in query optimisation

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Run EXPLAIN ANALYZE and spot scans, sorts and index use
L2 Design single and composite indexes for real queries; read row estimates
L3 Explain cost models, statistics, selectivity, join algorithms, index-only scans and parallel query
L4 Diagnose bad estimates, unusable indexes (functions, casts), plan regressions and memory spills
L5 Design indexing strategies and query patterns for a whole workload, balancing reads and writes
L6 Run performance management for a fleet (query monitoring, regression detection, review gates)

How the optimiser thinks

The optimiser's job

Given a declarative query, the optimiser must choose:

  1. An access path per table: sequential scan, an index scan using which index, a bitmap scan, or an index-only scan.
  2. A join order: for n tables there are up to n! orders (and many more tree shapes).
  3. A join algorithm per join: nested loop, hash or merge.
  4. How to aggregate and sort: hash aggregate or sort plus group aggregate, top-N heapsort, incremental sort, and parallelism.

It estimates the cost of candidate plans and picks the cheapest. The estimate rests on two things: how many rows each step produces (cardinality), and what each operation costs per row and per page. Almost every bad plan traces back to a cardinality misestimate. The algorithms are fine; the inputs are wrong.

Selectivity, cardinality and statistics

  • Selectivity: the fraction of rows a predicate keeps. id = 42 on a unique column is about 1/N. status = 'PAID' might be 0.8, and country = 'IS' 0.001.
  • Cardinality: here, the estimated number of rows out of a plan node (rows × selectivity). Elsewhere it also means the number of distinct values in a column ("high-cardinality column": many distinct values). Context tells you which.

PostgreSQL's ANALYZE samples each table (30,000 rows at the default default_statistics_target = 100) and stores per-column statistics in pg_statistic (readable through pg_stats):

SQL
SELECT attname, null_frac, n_distinct, most_common_vals, most_common_freqs, histogram_bounds, correlation
FROM pg_stats WHERE tablename = 'orders' AND attname IN ('status', 'created_at', 'customer_id');
Statistic Used for
null_frac IS NULL predicates
n_distinct Equality on non-MCV values: selectivity ≈ (1 − MCV share) / remaining distinct count. Also join size and group count estimates
MCV (most common values + frequencies) Equality on frequent values: skewed data such as status = 'PAID'
Histogram (equal-population bucket bounds) Range predicates (created_at > …)
correlation (physical order versus value order, −1 to 1) Index scan cost: high correlation means sequential-like heap access

Where estimates go wrong, and the fixes:

Cause Fix
Stale statistics (a bulk load, fast growth) ANALYZE after big changes; tune autovacuum analyse thresholds (chapter 57)
Skewed columns with more distinct values than the MCV list holds ALTER TABLE … ALTER COLUMN … SET STATISTICS 1000; then ANALYZE
Correlated columns (city and postcode, country and currency): the planner multiplies selectivities as if independent and underestimates CREATE STATISTICS orders_cc (dependencies, mcv) ON country, currency FROM orders;
Expressions and functions (lower(email) = $1, date_trunc(…)) Expression indexes gather statistics on the expression too; or create extended statistics on expressions (PG 14+)
Joins: misestimates multiply up the plan tree Fix the leaves first; sometimes restructure the query (CTEs with MATERIALIZED, temporary tables with ANALYZE for complex reports)
Opaque functions, table-valued functions, jsonb fields ROWS estimates on functions; expression statistics; promote hot JSON fields to columns

Physical operators

Scans

Scan How When it wins
Sequential scan Read every page in order A large fraction of rows is needed (beyond a few %), small tables, or no usable index. Sequential I/O is fast, and PostgreSQL 18's async I/O makes it faster still
Index scan Descend the B-tree, then fetch each matching heap tuple Few rows (high selectivity), or ordered output (ORDER BY … LIMIT)
Index-only scan Answer from the index alone (visibility map permitting) The index covers all needed columns (chapter 58)
Bitmap index scan + bitmap heap scan Collect matching TIDs from one or more indexes into a bitmap (OR/AND-able), then read heap pages in physical order, once each Medium selectivity; combining several indexes (a = 1 OR b = 2, or two single-column indexes ANDed)
Skip scan (PostgreSQL 18; Oracle and MySQL 8.0.13+ have had variants) Use a multicolumn index without a predicate on the leading column, by iterating its distinct values Low-cardinality leading column

Random versus sequential I/O is why an index isn't always faster. Fetching 30% of a table through an index means hundreds of thousands of random heap page reads, while a sequential scan reads each page once. The crossover point depends on random_page_cost (set it to about 1.1 on SSDs) and on the cache.

Join algorithms

nested loop for each outer row:probe inner (index) cost ≈ outer × probe wins: few outer rows+ indexed inner;LIMIT queries; anyjoin condition hash join 1 build: hash thesmaller input 2 probe: stream thelarger input wins: big unsortedequi-joinsspills if hashexceeds work_mem merge join both inputs sortedon the join key advance two cursorsin step wins: large inputsalready ordered(indexes), or whenoutput is sorted MySQL added hash joins in 8.0.18 and has no merge join
The three join algorithms. Nested loop probes the inner side once per outer row (great with an index and few outer rows); hash join builds a hash table on the smaller input and probes it (great for large unsorted equi-joins); merge join walks two sorted inputs together.
Algorithm Cost shape Needs Danger
Nested loop O(outer × inner-probe) An index on the inner join key (or a tiny inner) Underestimated outer row counts: the planner expected 10 outer rows and got 1M, making a million index probes. The single most common catastrophic plan
Hash join O(build + probe), memory for the hash table Equality condition; work_mem (× hash_mem_multiplier) Spills to disk in batches when memory is short; the build side was misjudged as small
Merge join O(sort both, unless already sorted) + O(n + m) Sorted inputs (indexes or explicit sorts) Sorting large inputs is expensive

Join order matters as much as the algorithm: filter early, and join the most selective relations first so intermediate results stay small. With many joins (beyond join_collapse_limit, 8 by default), PostgreSQL stops reordering explicit JOINs exhaustively. Beyond geqo_threshold (12), it uses a genetic search.

Sorting and aggregation

  • Sort: an in-memory quicksort if it fits work_mem, otherwise an external merge sort on disk (Sort Method: external merge Disk: 512000kB in EXPLAIN). Top-N heapsort for ORDER BY … LIMIT n keeps only n rows. Incremental sort (PG 13+) uses an index that's already sorted by a prefix of the sort keys.
  • Avoid sorts with indexes: an index on (customer_id, created_at DESC) returns rows already ordered for WHERE customer_id = ? ORDER BY created_at DESC, and with LIMIT it stops early. That's the single most effective pattern for "latest N" queries.
  • Aggregation: HashAggregate (a hash table keyed by group, which can spill since PG 13) or GroupAggregate (over sorted input, streaming). Plain count(*) on a big table must still visit every row (or every index entry with an index-only scan). PostgreSQL keeps no row counter. Use pg_class.reltuples estimates when approximate is acceptable, or maintain counters.
  • Parallel query: sequential scans, index scans, hash joins and aggregates can run across worker processes (max_parallel_workers_per_gather), which is great for big analytical queries on OLTP replicas.

Indexing strategy

Indexes for real queries

Indexes serve specific query shapes. Design them from the workload (pg_stat_statements), not from the schema.

Composite (multicolumn) indexes: column order matters. A B-tree on (a, b, c) is sorted by a, then b within each a, then c:

Query predicate Can use (a, b, c)?
a = ? Yes
a = ? AND b = ? Yes
a = ? AND b > ? Yes (equality first, then a range)
a = ? AND c = ? Partly: seek on a, filter c within it
b = ? Traditionally no. Skip scan (PG 18) can, if a has few distinct values
a > ? AND b = ? The range on a limits the useful seek. b filters within the range
ORDER BY a, b / WHERE a = ? ORDER BY b Yes, with no sort

Rules of thumb for column order:

  1. Equality columns first, then one range or sort column.
  2. Among equality columns, order by query reuse (which leading prefixes other queries need) more than by selectivity alone.
  3. Columns used only for output go in INCLUDE (covering), not in the key.
  4. Don't create (a) when (a, b) exists: the composite serves a-only queries too (at slightly higher cost).
SQL
-- Workload: "a customer's latest orders, optionally by status", the hottest query in the app
CREATE INDEX CONCURRENTLY orders_cust_created ON orders (customer_id, created_at DESC) INCLUDE (status, total_cents);
-- Serves: WHERE customer_id = $1 ORDER BY created_at DESC LIMIT 20   → index-only, no sort, stops after 20

-- Partial index: the workers' queue only ever looks at READY jobs (a tiny fraction of the table)
CREATE INDEX CONCURRENTLY jobs_ready ON jobs (priority DESC, id) WHERE status = 'READY';

-- Expression index: case-insensitive lookups
CREATE UNIQUE INDEX CONCURRENTLY users_email_lower ON users (lower(email));
SELECT * FROM users WHERE lower(email) = lower($1);     -- the predicate must match the expression exactly

Selectivity and indexes: an index on a boolean or low-cardinality column (is_deleted) rarely helps on its own. Each value matches a huge fraction of rows. Use a partial index for the rare value (WHERE is_deleted = false when queries always filter it), or a composite index with a selective leading column.

Covering indexes (INCLUDE, or all needed columns in the key) enable index-only scans. They cost space and write amplification, and in PostgreSQL they disable HOT updates if the included columns change (chapter 58).

Prepared statements, generic plans and parameter sensitivity

When a statement is prepared (most drivers do this, and JDBC drivers do it after a threshold), the database can reuse a plan:

  • PostgreSQL plans the first 5 executions with the actual parameter values (custom plans), then switches to a generic plan if it isn't estimated to be worse. Generic plans can be bad for skewed parameters: status = $1 where 'PAID' is 80% of rows and 'DISPUTED' is 0.01%. Control it with plan_cache_mode = force_custom_plan per role or session, or rewrite.
  • SQL Server's "parameter sniffing" problem is the same issue. Remedies there include OPTION (RECOMPILE), OPTIMIZE FOR, and Query Store plan forcing. SQL Server 2022 added parameter-sensitive plan optimisation (multiple cached plans).
  • Oracle has adaptive cursor sharing and bind peeking. MySQL re-plans per execution, with a smaller optimiser search space.

Anti-patterns

Anti-pattern Why it's slow Better
WHERE date(created_at) = '2026-10-24', WHERE lower(email) = … without an expression index, WHERE id + 0 = 5 Function or arithmetic on the column → non-sargable A half-open range on the raw column, or an expression index
Implicit casts: WHERE varchar_col = 123, comparing uuid to text, the JDBC setString on a uuid column, MySQL utf8 versus utf8mb4 collation mismatch in joins The column is converted per row, so the index can't be used Bind the right type; match collations and types across join columns
LIKE '%term%' No prefix → a B-tree can't help pg_trgm GIN index, or full-text search (chapter 56)
OFFSET 100000 Scans and discards 100,000 rows Keyset pagination
SELECT * Fetches wide and TOASTed columns, defeats index-only scans, breaks when columns change List the columns
OR across different columns (a = 1 OR b = 2) Needs a BitmapOr of two indexes, or a full scan Indexes on both (BitmapOr), or a UNION ALL rewrite
NOT IN (subquery) NULL semantics block the anti-join optimisation NOT EXISTS
count(*) to check existence Counts everything EXISTS (…) / LIMIT 1
N+1 queries from the ORM Thousands of round trips Joins, batch fetching, = ANY($1) (Vol. 3 ch. 49)
Huge IN (…) lists built as strings Parse and plan cost; plan cache pollution = ANY($1::bigint[]), or join against VALUES or a temporary table
Unbounded queries (no LIMIT, no date range) Grow with data forever Bound every user-facing query
Correlated subquery per row in SELECT on big result sets Executes per row A LATERAL join or a pre-aggregated join
Long transactions around queries Hold snapshots, cause bloat, keep locks Keep transactions short

The workflow

From slow query to fix

The roadmap's workflow, made concrete:

Text
slow query → EXPLAIN ANALYZE → bottleneck → hypothesis → index/query/schema change → benchmark

1. Find the queries that matter. Optimise by total impact (calls × mean time), not by the scariest single query:

SQL
SELECT left(query, 80) AS q, calls,
       round(total_exec_time::numeric / 1000, 1) AS total_s,
       round(mean_exec_time::numeric, 2) AS mean_ms,
       round(100 * total_exec_time / sum(total_exec_time) OVER (), 1) AS pct,
       rows / greatest(calls, 1) AS rows_per_call,
       shared_blks_read + shared_blks_hit AS blocks
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 15;

Also collect slow-query logs (log_min_duration_statement, auto_explain with log_analyze) and APM traces linking slow endpoints to queries (Vol. 2 ch. 32). MySQL has the slow query log and performance_schema/sys schema; SQL Server has Query Store and DMVs; Oracle has AWR/ASH reports.

2. Get the real plan with realistic parameters, on production-like data. Run EXPLAIN (ANALYZE, BUFFERS) on a replica or staging environment with production-sized data. Plans on tiny development databases are meaningless.

3. Find the bottleneck node: the one with the most time (inclusive of children, times loops) or the most buffers. Then check:

  • Estimated versus actual rows: a mismatch means a statistics problem (fix that first; everything above it in the tree is built on the wrong number).
  • Rows Removed by Filter large relative to rows returned: an index is needed (or a better one).
  • Nested Loop with a large loops count over an inner index or sequential scan: a misestimate, or a missing index for a hash or merge join.
  • Sort / Hash with Disk usage: work_mem, or avoid the sort with an index.
  • Seq Scan on a big table returning few rows: a missing or unusable index (type mismatch, function on the column).
  • Heap Fetches high in an index-only scan: vacuum or visibility map.
  • High shared read (I/O bound): the working set exceeds the cache; reduce pages touched.

4. Form one hypothesis ("the planner seq-scans because the predicate casts the uuid column to text") and make one change: an index, a query rewrite, statistics, schema, or configuration.

5. Benchmark: re-run EXPLAIN ANALYZE (warm the cache comparably; run it several times), check pg_stat_statements after deploying, and watch write costs too (a new index slows inserts). For broader changes, use pgbench with custom scripts, or replay real traffic.

A worked example

SQL
-- Endpoint: "orders needing attention for a merchant", p99 2.8 s
SELECT o.id, o.created_at, o.total_cents, c.email
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE o.merchant_id = $1
  AND o.status IN ('PAYMENT_FAILED', 'DISPUTED')
  AND o.created_at >= now() - interval '30 days'
ORDER BY o.created_at DESC
LIMIT 50;
Text
Limit (actual time=2790..2791 rows=50)
  -> Sort (actual rows=50) Sort Key: o.created_at DESC  Sort Method: top-N heapsort
     -> Nested Loop (actual rows=1312 loops=1)
        -> Bitmap Heap Scan on orders o (rows=1200 est) (actual rows=1312)
              Recheck Cond: (merchant_id = 77)
              Filter: (status = ANY (…) AND created_at >= …)
              Rows Removed by Filter: 1843021                 ← read 1.8M rows of this merchant to keep 1.3K
              Buffers: shared hit=12011 read=98455             ← ~770 MB of page reads
              -> Bitmap Index Scan on orders_merchant_idx (actual rows=1844333)
        -> Index Scan using customers_pkey on customers c (actual rows=1 loops=1312)
  • Bottleneck: reading all 1.8M orders of a large merchant and filtering by status and date. The rare statuses (well under 1%) are the selective part, but no index exists for them.
  • Hypothesis: a partial index for the "attention" statuses, ordered by merchant and date, makes this an index range scan of about 1,300 entries with no sort.
SQL
CREATE INDEX CONCURRENTLY orders_attention
  ON orders (merchant_id, created_at DESC)
  WHERE status IN ('PAYMENT_FAILED', 'DISPUTED');
ANALYZE orders;
Text
Limit (actual time=0.41..0.88 rows=50)
  -> Nested Loop (actual rows=50)
     -> Index Scan using orders_attention on orders o (actual rows=50)    ← stops after 50, already ordered
           Index Cond: (merchant_id = 77 AND created_at >= …)
     -> Index Scan using customers_pkey on customers c (actual rows=1 loops=50)
Execution Time: 0.95 ms
  • Benchmark: 2,790 ms → under 1 ms. The index is tiny, since it only holds rare statuses, so the write overhead is negligible. Confirm with pg_stat_statements after deploying.
  • Generalising: the query's selective predicate wasn't indexed. The planner did the best it could with merchant_id alone. Rare-value filters plus "latest N" ordering are the textbook case for a partial composite index.

Beyond indexes

When indexing isn't enough:

  • Reduce the work: pre-aggregate with materialised views (refreshed periodically, or REFRESH MATERIALIZED VIEW CONCURRENTLY) or summary tables maintained incrementally; denormalise a hot read path (chapter 55).
  • Cache results (Vol. 3 ch. 53), or move read load to replicas (chapter 61).
  • Partition to prune old data (chapter 57).
  • Change the data model: a JSON field queried constantly becomes a column; an EAV table becomes typed columns.
  • Move analytics out of the OLTP database into a column store (chapter 58).
  • Configuration: work_mem for sorts and hashes, random_page_cost on SSDs, effective_cache_size, parallelism. Configuration is the last resort for a single query, but the first sanity check for a new server.

Lab: indexes that work, indexes that don't

PostgreSQL 16 with 3 million orders (o2) and 200,000 customers (c2), best of five runs. Each experiment is a common reason an "indexed" query is still slow.

Experiment 1: composite index column order

300 orders have the rare status DISPUTED. Query: the first 20 since March 2025, in date order.

SQL
SELECT id FROM o2 WHERE status = 'DISPUTED' AND placed_at >= '2025-03-01' ORDER BY placed_at LIMIT 20;
Text
only an index on (placed_at): 17.78 ms via Index Scan using o2_placed, 5881 buffers
index (placed_at, status):     4.24 ms via Index Scan using ix,        960 buffers
index (status, placed_at):     0.27 ms via Index Scan using ix,         23 buffers

With placed_at first, the index can deliver rows in date order but must walk through every date since March and check each entry's status: hundreds of pages to find 20 rare matches. With the equality column first, the matching entries are contiguous and already sorted by date, so the scan reads exactly what it needs. The rule of thumb for composite B-trees: equality columns first, then the range or sort column; and a composite index also serves queries on its leading columns alone, but not on its trailing ones (PostgreSQL 18's skip scan softens this when the leading column has few distinct values).

Experiment 2: conditions that can't use an index

Text
lower(email) = '…' with an index on email              :    30.08 ms via Parallel Seq Scan
date(placed_at at time zone 'UTC') = '2026-03-01'      :   169.04 ms via Parallel Seq Scan
placed_at >= '2026-03-01' AND < '2026-03-02' (range)   :     0.66 ms via Index Only Scan using o2_placed
id = 4242.0 (numeric literal against bigint)           :   146.05 ms via Parallel Seq Scan
id = 4242                                              :     0.08 ms via Index Scan using o2_pkey
after CREATE INDEX ON c2 (lower(email)):                     0.09 ms via Index Scan using c2_lower_email

An index on email stores email values; it can't answer questions about lower(email) or a date computed from placed_at, so the planner scanned. Fixes: an expression index on exactly the expression (lower(email)), or rewriting the condition so the bare column is compared (the half-open range for "that day" was 256× faster). The 4242.0 case is the subtle one: a numeric literal made PostgreSQL compare id::numeric = 4242.0, a function on the column, and the primary key went unused: 1,800× slower. ORMs and drivers that bind parameters with the wrong type cause exactly this; check the types your driver sends.

Experiment 3: correlated columns fool the planner

Cities and pincode prefixes are perfectly correlated (every Chennai customer has a 600 pincode):

Text
city = 'Chennai' AND left(pincode,3) = '600': estimated 121 rows, actual 25000
after CREATE STATISTICS (dependencies, mcv) ON city, left(pincode, 3): estimated 25133 rows

By default the planner assumes conditions are independent and multiplies their selectivities: 1/8 of customers are in Chennai × a small fraction have prefix 600 → 121 rows. Reality was 200× more. Inside a larger query, an estimate that low makes the planner choose a nested loop where a hash join was needed, which is how one innocent filter turns a 50 ms query into a 50 s one. Extended statistics (functional dependencies and multi-column most-common values) taught the planner the correlation. Look for this whenever estimated and actual rows diverge on multi-column filters.

Experiment 4: index-only scans depend on VACUUM

A covering index ((customer_id) INCLUDE (total_paise)) contains every column the query needs:

Text
covering index, just after VACUUM:               heap fetches 0,     4.689 ms
after updating those rows, before VACUUM:        heap fetches 60030, 255.901 ms
after VACUUM again:                              heap fetches 0,     4.437 ms

An index-only scan can skip the table only for pages the visibility map marks as all-visible, because the index doesn't store MVCC information. After the update, those pages weren't all-visible, so each of 60,030 rows needed a trip to the heap: 55× slower with the same plan name. Tables with frequent updates rarely get the full benefit; keep autovacuum aggressive on them, and check Heap Fetches in plans.

Experiment 5: searching inside strings

Text
email LIKE '%4242%' with a B-tree on email: 15.6 ms via Seq Scan
with a GIN trigram index:                   0.18 ms via Bitmap Index Scan on c2_trgm

A B-tree can serve LIKE 'User42%' (a prefix, with the right operator class or C collation) but not a pattern with a leading wildcard. The pg_trgm extension indexes every three-character substring in a GIN index, so %4242% becomes a lookup of the trigrams 424 and 242: 87× faster here. Trigram indexes also power similarity search (% operator, similarity()), useful for typo-tolerant name search; for full-text relevance search, see chapter 63.

Try it yourself

  1. Enable pg_stat_statements (shared_preload_libraries), run a pgbench workload plus your own queries, and list the top five by total_exec_time.
  2. Run experiment 2's numeric-literal query with EXPLAIN and find the cast in the filter line. Then try WHERE id = $1 with a Python Decimal parameter.
  3. Set work_mem = '64kB' and run a large ORDER BY; find Sort Method: external merge Disk: in the plan, then raise work_mem for that session only.
  4. Write a query that's fast with one parameter value and slow with another (a skewed column), and observe generic versus custom plans with PREPARE after six executions.

Revision sheet: query optimisation

Key ideas

  • Cost-based planning: enumerate plans (join orders, access paths, join methods), estimate cardinalities from statistics, choose the cheapest; genetic optimiser beyond geqo_threshold tables.
  • Statistics: per-column null fraction, n_distinct, most common values, histograms, correlation; extended statistics (dependencies, ndistinct, MCV); default_statistics_target; ANALYZE after bulk changes.
  • Access paths: sequential scan, index scan, index-only scan (visibility map), bitmap index/heap scan (combining indexes), TID scans; parallel variants.
  • Join methods: nested loop (indexed inner side), hash join (memory: work_mem, batches), merge join (sorted inputs).
  • Other nodes: sort (in memory or external), hash aggregate vs group aggregate, materialise, memoize, gather.
  • Indexing strategy: equality-then-range composite order, covering (INCLUDE), partial indexes (WHERE status = 'NEW'), expression indexes, operator classes (text_pattern_ops, trigram GIN), avoiding redundant and unused indexes (pg_stat_user_indexes.idx_scan).
  • Workflow: pg_stat_statements, auto_explain, EXPLAIN (ANALYZE, BUFFERS), estimate vs actual, fix, verify; plan stability (prepared statement generic plans).

Numbers to remember

  • Lab: equality-first composite index 16× faster than range-first (23 vs 960 buffers); a numeric literal against a bigint key made a lookup 1,800× slower; independent-columns assumption underestimated by 200×; index-only scan 55× slower with an outdated visibility map; trigram GIN 87× faster for %x%.

Pitfalls

  • Functions or casts on indexed columns; mismatched parameter types from drivers.
  • Wrong composite column order; indexes on low-selectivity columns alone.
  • Stale statistics after bulk loads; correlated predicates without extended statistics.
  • Testing plans on tiny datasets; reading cost as milliseconds.
  • Too many indexes on write-heavy tables; never dropping unused ones.
  • OFFSET pagination and SELECT * defeating index-only scans.

Glossary

  • Cardinality estimate: predicted number of rows from a plan node.
  • Selectivity: fraction of rows a condition keeps.
  • Index-only scan: answering from the index without visiting the heap.
  • Bitmap scan: collecting matching row locations from indexes, then reading heap pages in order.
  • Covering index: an index containing all columns a query needs.
  • Generic plan: a cached plan for a prepared statement that ignores specific parameter values.