Database Optimization & Storage9 min readUpdated: 2024-12-30

Measuring Database Query Performance & Selecting Indexes from Execution Plans

Using EXPLAIN ANALYZE, composite indexing order, and partition pruning to cut relational query latencies from seconds to milliseconds.

PostgreSQLQuery OptimizationIndexingPerformanceSQL

Core Takeaway

Adding indexes randomly when queries feel sluggish often slows down write operations without fixing the root bottleneck. True query optimization requires understanding database execution plans (EXPLAIN ANALYZE), matching column order in composite indexes to query predicates, and avoiding anti-patterns like function-wrapped index columns.

Problem Statement & Context

In high-traffic platforms, a single poorly indexed query can saturate database CPU, exhaust connection pools, and bring an entire backend down. In this note, we examine real techniques used to diagnose slow queries and design optimal indexing strategies.

Architectural Concepts & Implementation

1. Reading PostgreSQL EXPLAIN (ANALYZE, BUFFERS) Output

Never optimize a query based on intuition. Always run EXPLAIN (ANALYZE, BUFFERS) to see actual execution times, node types (Seq Scan vs. Index Scan vs. Bitmap Heap Scan), and buffer hit ratios.

Inspecting Query Execution Plans
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, title, published_at, view_count
FROM articles
WHERE status = 'PUBLISHED'
  AND published_at >= '2024-01-01'
ORDER BY published_at DESC
LIMIT 50;

-- Look for:
-- 1. "Seq Scan on articles" -> Indicates missing index on status or published_at
-- 2. "Rows Removed by Filter: 150000" -> Table scan reading and discarding huge row volumes
-- 3. "Buffers: shared hit=4210 read=12900" -> Heavy disk I/O reading table pages into memory

2. Column Ordering in Composite Indexes

In a composite index (col_a, col_b, col_c), column order matters tremendously. Follow the Equality-First Rule: place columns used in equality checks (=) first, followed by columns used in range filters (>, <, BETWEEN), and finally columns needed for sorting (ORDER BY).

Optimal Composite Index Definition
-- Sub-optimal index:
-- CREATE INDEX idx_articles_bad ON articles (published_at, status);
-- PostgreSQL must scan the range of published_at first, then filter by status!

-- Optimal index adhering to equality-first rule:
CREATE INDEX idx_articles_optimal ON articles (status, published_at DESC)
INCLUDE (title, view_count);
-- 'status' equality matches immediately,
-- 'published_at' satisfies both range condition and ORDER BY sort without a Sort node,
-- 'INCLUDE' allows an Index Only Scan without hitting table heap pages!

3. Avoiding Partial Scans Caused by Function Wrapping

Wrapping an indexed column in a function (e.g., WHERE LOWER(email) = $1 or WHERE DATE(created_at) = $1) invalidates standard b-tree indexes, forcing a full table scan. Instead, use expression indexes or range comparisons.

Common Pitfalls & Trade-offs

  • !Trade-off: Index write overhead. Every INSERT, UPDATE, or DELETE on a table must update all associated indexes. Maintain only indexes that support high-frequency or mission-critical queries.
  • !Pitfall: Low-cardinality leading index columns. Creating an index on a boolean column alone (is_active) rarely helps because the query planner will prefer a sequence scan if 80% of rows have is_active = true. Use partial indexes instead.

Production Verification Checklist

  • Profile queries using EXPLAIN (ANALYZE, BUFFERS) before and after adding indexes.
  • Apply the equality-first rule when designing composite index column orders.
  • Use partial indexes for queries that consistently filter by a specific status subset.
  • Leverage INCLUDE clauses for index-only scans on frequently selected columns.
  • Monitor index usage periodically using pg_stat_user_indexes and drop unused indexes.
Back to all engineering notes