SQL Query Optimization: Mastering Execution Plans and Indexing Strategies

Slow database queries rarely stem from raw hardware limits; they almost always come from unindexed table scans, poorly ordered composite indexes, or non-sargable predicates that force the query planner to inspect millions of rows. Adding random single-column indexes bloats disk storage and slows down INSERT and UPDATE throughput without fixing read latency.

Reading EXPLAIN (ANALYZE, BUFFERS) execution plans removes the guesswork. By inspecting actual row estimates, join algorithms, and shared buffer hits, you can design targeted B-tree, covering, and partial indexes that cut query latency from seconds to sub-milliseconds.

Comparing SQL Index Structures and Access Methods

Choosing the right index type depends on data cardinality, predicate operators, and write frequency:

Index TypeUnderlying StructureBest Query PatternsStorage & Write Overhead
B-Tree (Default)Balanced search treeEquality (=), range (<, >, BETWEEN), ORDER BYModerate; scales well for OLTP
Composite B-TreeMulti-column sorted treeMulti-column WHERE + ORDER BY (left-most prefix rule)Moderate-High; replaces multiple single indexes
Covering Index (INCLUDE)B-Tree + leaf payload columnsIndex-Only Scans avoiding heap table lookupsHigher leaf size; eliminates random heap I/O
Partial Index (WHERE)Filtered B-Tree subsetHot status subsets (e.g., status = 'pending')Minimal; skips indexing cold/archived rows
GIN (Generalized Inverted)Inverted posting listsJSONB containment (@>), arrays, full-text searchHigh write cost; fast multi-key lookups

Setting Up a Realistic Benchmark Schema (schema_seed.sql)

To inspect planner behavior accurately, create an orders table with 1,000,000 rows exhibiting realistic skew across customer IDs, order statuses, and timestamps:

SQL
CREATE TABLE orders (
    order_id BIGSERIAL PRIMARY KEY,
    tenant_id INT NOT NULL,
    customer_id INT NOT NULL,
    status VARCHAR(20) NOT NULL,
    total_amount NUMERIC(10, 2) NOT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

INSERT INTO orders (tenant_id, customer_id, status, total_amount, created_at)
SELECT
    (random() * 50)::INT + 1 AS tenant_id,
    (random() * 100000)::INT + 1 AS customer_id,
    CASE
        WHEN random() < 0.85 THEN 'completed'
        WHEN random() < 0.95 THEN 'shipped'
        ELSE 'pending'
    END AS status,
    ROUND((random() * 500 + 10)::NUMERIC, 2) AS total_amount,
    NOW() - (random() * INTERVAL '365 days') AS created_at
FROM generate_series(1, 1000000);

ANALYZE orders;

Reading EXPLAIN (ANALYZE, BUFFERS) Execution Plans

Suppose an API endpoint fetches the 20 most recent pending orders for a specific tenant_id. Before adding indexes, run EXPLAIN (ANALYZE, BUFFERS) to observe the baseline plan:

SQL
EXPLAIN (ANALYZE, BUFFERS)
SELECT order_id, customer_id, total_amount, created_at
FROM orders
WHERE tenant_id = 14
  AND status = 'pending'
ORDER BY created_at DESC
LIMIT 20;

A baseline unindexed execution plan reveals a parallel sequential scan and an external/top-N sort:

TEXT
Limit  (cost=16842.15..16842.20 rows=20 width=28) (actual time=84.312..84.318 rows=20 loops=1)
  Buffers: shared hit=1240 read=7105
  ->  Sort  (cost=16842.15..16844.52 rows=948 width=28) (actual time=84.310..84.313 rows=20 loops=1)
        Sort Key: created_at DESC
        Sort Method: top-N heapsort  Memory: 26kB
        ->  Seq Scan on orders  (cost=0.00..16816.00 rows=948 width=28) (actual time=0.042..83.910 rows=1012 loops=1)
              Filter: ((tenant_id = 14) AND ((status)::text = 'pending'::text))
              Rows Removed by Filter: 998988
              Buffers: shared hit=1240 read=7105
Planning Time: 0.185 ms
Execution Time: 84.356 ms

Three critical signals stand out in this output:

  1. Rows Removed by Filter: 998988: PostgreSQL read 8,345 8KB pages (66.7 MB) from disk/cache to keep only 1,012 rows.
  2. Sort Method: top-N heapsort: Because rows arrived unsorted from the heap, the engine had to sort all matching rows in memory before applying LIMIT 20.
  3. Buffers: shared read=7105: Physical disk reads dominated execution time.

Designing Composite, Covering, and Partial Indexes

Follow the Equality -> Sort -> Range (ESR) column ordering rule when building composite B-tree indexes:

  1. Equality predicates first (tenant_id): Narrows the B-tree search to a single contiguous leaf range.
  2. Sort or Range columns next (created_at DESC): Allows the engine to walk leaf nodes in pre-sorted order and stop immediately after reading 20 rows (Limit).
  3. Partial filter (WHERE status = 'pending'): Since 85% of rows are completed, filtering on status = 'pending' shrinks the index footprint by ~95%.
  4. Covering payload (INCLUDE): Attaches customer_id and total_amount to the leaf pages so PostgreSQL never visits the main table heap.
SQL
CREATE INDEX CONCURRENTLY idx_orders_tenant_pending_created_cov
ON orders (tenant_id, created_at DESC)
INCLUDE (customer_id, total_amount)
WHERE status = 'pending';

ANALYZE orders;

Re-running the exact same EXPLAIN (ANALYZE, BUFFERS) query now produces an Index Only Scan:

TEXT
Limit  (cost=0.29..14.82 rows=20 width=28) (actual time=0.038..0.054 rows=20 loops=1)
  Buffers: shared hit=4
  ->  Index Only Scan using idx_orders_tenant_pending_created_cov on orders  (cost=0.29..735.10 rows=1012 width=28) (actual time=0.036..0.050 rows=20 loops=1)
        Index Cond: (tenant_id = 14)
        Heap Fetches: 0
        Buffers: shared hit=4
Planning Time: 0.210 ms
Execution Time: 0.079 ms

Execution time dropped from 84.35 ms to 0.079 ms (a >1,000x speedup), buffer reads fell from 8,345 pages to 4 pages, and Heap Fetches: 0 confirms zero table heap lookups.

Rewriting Non-Sargable Queries (optimize_queries.sql)

Even the best index will be ignored if a query wraps indexed columns in functions or uses leading wildcards—known as non-sargable (Search ARGument ABLE) predicates.

SQL
-- BAD: Wrapping created_at in DATE() prevents B-tree index usage
SELECT COUNT(*)
FROM orders
WHERE tenant_id = 14
  AND DATE(created_at) = '2026-11-15';

-- GOOD: Half-open timestamp range preserves B-tree index range scans
SELECT COUNT(*)
FROM orders
WHERE tenant_id = 14
  AND created_at >= '2026-11-15 00:00:00+00'
  AND created_at < '2026-11-16 00:00:00+00';

-- BAD: Offset pagination degrades linearly (O(N)) on deep pages
SELECT order_id, created_at, total_amount
FROM orders
WHERE tenant_id = 14
ORDER BY created_at DESC, order_id DESC
LIMIT 20 OFFSET 50000;

-- GOOD: Keyset (cursor) pagination stays O(log N) at any depth
SELECT order_id, created_at, total_amount
FROM orders
WHERE tenant_id = 14
  AND (created_at, order_id) < ('2026-06-12 14:22:09+00', 482910)
ORDER BY created_at DESC, order_id DESC
LIMIT 20;

Auditing Unused and Bloated Indexes in Production

Every active index adds write amplification to INSERT, UPDATE, and DELETE statements. Run periodic catalog diagnostics to identify unused indexes and missing foreign-key indexes:

SQL
-- Identify non-unique indexes with zero scans since last stats reset
SELECT
    schemaname || '.' || relname AS table_name,
    indexrelname AS index_name,
    pg_size_pretty(pg_relation_size(indexrelid)) AS index_size,
    idx_scan AS total_scans
FROM pg_stat_user_indexes
WHERE idx_scan = 0
  AND indexrelid NOT IN (
      SELECT conindid FROM pg_constraint WHERE contype IN ('p', 'u')
  )
ORDER BY pg_relation_size(indexrelid) DESC;

Best Practices for SQL Performance Tuning

  • Always build production indexes with CREATE INDEX CONCURRENTLY: Standard CREATE INDEX acquires a SHARE lock that blocks all writes (INSERT/UPDATE/DELETE) until the build completes.
  • Keep VACUUM aggressive on tables using Index-Only Scans: PostgreSQL relies on the Visibility Map to skip heap fetches; if autovacuum lags behind heavy updates, Heap Fetches will climb and degrade Index-Only Scans back into regular Index Scans.
  • Inspect BUFFERS alongside timing: Wall-clock time fluctuates with OS page cache warmth, whereas shared hit + read block counts provide a deterministic measure of I/O work.
  • Consolidate redundant left-prefix indexes: An index on (tenant_id, created_at) already accelerates queries filtering solely on tenant_id, making a standalone index on (tenant_id) redundant.

Common Mistakes

  • Indexing low-cardinality boolean or status columns alone: Creating a standalone B-tree index on status where 85% of rows share 'completed' forces expensive random heap reads that perform worse than a sequential scan.
  • **Using SELECT * with covering indexes:** Fetching unused columns prevents PostgreSQL from satisfying the query via Index Only Scan, forcing a heap lookup for every matched row.
  • Testing queries on tiny local datasets: With 500 rows in a dev container, the planner will almost always choose a Seq Scan because reading one 8KB page is faster than traversing an index. Always test plans against production-scale row counts and statistics.

Summary

Optimizing SQL queries relies on matching physical index structures to actual access paths verified through EXPLAIN (ANALYZE, BUFFERS). By ordering composite indexes with the Equality-Sort-Range rule, trimming index size with WHERE partial filters, eliminating heap lookups with INCLUDE covering columns, and keeping predicates sargable, engineering teams can sustain sub-millisecond query performance at scale.