Abbottabad, KPK
BlogNovember 5, 2026

Mastering Database Performance: PostgreSQL Indexing, Query Plans & Optimization

Haseeb Gul
When web applications begin experiencing slow response times and high server CPU usage, developers often look first at frontend bundles or backend API logic. In reality, the database is almost always the true bottleneck. A query that takes 15ms on a development dataset of 5,000 rows can degrade to 3,500ms when executed against 5,000,000 rows in production. Throwing more memory or CPU at the database server is an expensive band-aid; real scalability requires understanding how PostgreSQL plans and executes queries, choosing the right index structures, and eliminating costly I/O operations. Before optimizing queries, you must understand the journey a SQL statement takes inside PostgreSQL:
Text
+---------------------------------------------------------------+
|                 POSTGRESQL QUERY PIPELINE                     |
|                                                               |
|  SQL Query --> [ 1. Parser ]      Syntax validation & AST     |
|                       |                                       |
|                       v                                       |
|                [ 2. Rewriter ]    Applies rules & view expansion
|                       |                                       |
|                       v                                       |
|                [ 3. Planner ]     Evaluates paths & costs     |
|                       |           (Statistics from pg_statistic)
|                       v                                       |
|                [ 4. Executor ]    Executes nodes, reads       |
|                                   shared buffers / disk       |
+---------------------------------------------------------------+
The Planner (Optimizer) is the brain of PostgreSQL. It generates multiple execution strategies (hash joins, nested loops, sequential scans, index scans) and calculates an estimated cost for each based on table statistics stored in pg_statistic (updated via ANALYZE). The strategy with the lowest estimated cost is passed to the Executor.
The single most important command for database optimization is EXPLAIN. When debugging performance, never run bare EXPLAIN; always use ANALYZE and BUFFERS:
Sql
EXPLAIN (ANALYZE, BUFFERS, VERBOSE, SETTINGS)
SELECT id, user_id, total_cents, created_at
FROM orders
WHERE status = 'completed' AND created_at >= '2026-01-01'
ORDER BY created_at DESC
LIMIT 50;
  • ANALYZE: Actually runs the query, reporting real wall-clock execution times alongside planner estimates.
  • BUFFERS: Displays shared memory buffer hits, reads from disk, and writes.
Consider this example output:
Text
Limit  (cost=142.15..142.27 rows=50 width=36) (actual time=2.140..2.155 rows=50 loops=1)
  Buffers: shared hit=84 read=12
  ->  Sort  (cost=142.15..145.80 rows=1460 width=36) (actual time=2.138..2.145 rows=50 loops=1)
        Sort Key: created_at DESC
        Sort Method: top-N heapsort  Memory: 30kB
        Buffers: shared hit=84 read=12
        ->  Bitmap Heap Scan on orders  (cost=42.10..112.50 rows=1460 width=36) (actual time=0.450..1.420 rows=1520 loops=1)
              Recheck Cond: ((status = 'completed'::text) AND (created_at >= '2026-01-01'::date))
              Buffers: shared hit=84 read=12
              ->  Bitmap Index Scan on idx_orders_status_date  (cost=0.00..41.73 rows=1460 width=0) (actual time=0.380..0.380 rows=1520 loops=1)
                    Index Cond: ((status = 'completed'::text) AND (created_at >= '2026-01-01'::date))
                    Buffers: shared hit=4
Planning Time: 0.185 ms
Execution Time: 2.210 ms
  1. cost=142.15..142.27:
    • 142.15 is the startup cost (cost to fetch the very first row).
    • 142.27 is the total cost (cost to return all rows for this node). Cost is an arbitrary unit where 1.0 equals a single sequential disk page fetch (seq_page_cost).
  2. actual time=0.450..1.420: Real time in milliseconds for first row returned and completion of that node.
  3. shared hit vs read:
    • shared hit: Pages found directly in PostgreSQL's RAM (shared_buffers). This is fast (microseconds).
    • read: Pages fetched from the OS page cache or disk. Disk reads are the primary cause of query latency.
Scan Type
Mechanism
Best For
Performance
Sequential Scan (Seq Scan)Reads every page in the table from start to finishSmall tables (<10k rows) or queries returning >20% of the tableO(N) - Slow on large tables
Index ScanNavigates index tree to find row pointers (TIDs), then fetches rows from the table heapSelective queries returning a small subset of rowsO(log N) - Fast for high selectivity
Index Only ScanFetches all requested columns directly from the index tree without touching table pagesQueries where all selected/filtered columns exist in index (requires valid visibility map)O(log N) - Maximum performance
Bitmap Index ScanBuilds a bitmap in RAM of matching page offsets, then reads table heap sequentiallyMultiple index conditions combined or queries returning 5-15% of tableO(log N) + efficient batch I/O
PostgreSQL offers specialized index data structures. Choosing the wrong type wastes disk storage and degrades write throughput without speeding up reads.
  • Under the Hood: Balanced search tree maintaining sorted order with self-balancing properties.
  • Supported Operators: <, <=, =, >=, >, BETWEEN, IN, IS NULL, and ORDER BY.
  • Best Used For: Primary keys, foreign keys, timestamps, numeric IDs, and equality checks.
Sql
-- Standard B-Tree Index on foreign key
CREATE INDEX idx_orders_user_id ON orders (user_id);
  • Under the Hood: Inverted index where each element maps to a list of rows containing that element.
  • Supported Operators: Array operations (&&, @>, <@), JSONB containment (@>, ?, ?&), and Full-Text Search (tsvector @@ tsquery).
  • Best Used For: Searching tags, JSONB documents, or text search catalogs.
Sql
-- GIN Index for fast JSONB metadata lookups
CREATE INDEX idx_products_specs_gin ON products USING gin (specifications jsonb_path_ops);

-- Query using JSONB containment:
SELECT title FROM products WHERE specifications @> '{"processor": "M3 Pro"}';
  • Under the Hood: Balanced, tree-structured access method acting as a base template for arbitrary indexing schemes.
  • Supported Operators: Geometric overlap (&&), containment (@>), distance/nearest-neighbor (<->), and range overlap (&&).
  • Best Used For: PostGIS spatial coordinates, IP address ranges (inet), and booking interval ranges (tstzrange).
Sql
-- GiST Index for room reservation conflict detection
CREATE TABLE reservations (
    id SERIAL PRIMARY KEY,
    room_id INT,
    during TSTZRANGE,
    EXCLUDE USING gist (room_id WITH =, during WITH &&)
);
  • Under the Hood: Stores only the minimum and maximum values for physical blocks of pages (default 128 pages per range).
  • Storage Footprint: 99% smaller than a B-Tree. A 50GB table might need a 5GB B-Tree index, but only a 5MB BRIN index!
  • Best Used For: Massive append-only tables where data is naturally correlated with physical storage order (e.g. created_at timestamps in event logs or sensor metrics).
Sql
-- BRIN index on a 100-million row append-only audit table
CREATE INDEX idx_audit_logs_created_brin ON audit_logs USING brin (created_at);
Standard single-column indexes only take you so far. High-performance systems use specialized indexing patterns to achieve microsecond lookups. An index does not need to index every row in a table. If 95% of your orders are "archived" or "completed" and your API only queries "pending" orders:
Sql
-- BAD: Indexes all 10,000,000 rows
CREATE INDEX idx_orders_status ON orders (status);

-- PRO: Indexes ONLY active rows (e.g., 20,000 rows)
CREATE INDEX idx_orders_pending_urgent 
ON orders (user_id, created_at) 
WHERE status = 'pending';
Benefits:
  • Index size drops from 400MB to 2MB.
  • Inserts and updates for "completed" orders suffer zero index write overhead.
  • Cache fits entirely inside RAM (shared_buffers).
To achieve an Index-Only Scan, the database must satisfy the entire query from the index without reading the table heap:
Sql
-- Query: Find user orders and retrieve total amount without heap lookup
CREATE INDEX idx_orders_user_covering 
ON orders (user_id, created_at) 
INCLUDE (total_cents, status);

-- Now this query touches ZERO table heap pages:
SELECT user_id, created_at, total_cents, status
FROM orders
WHERE user_id = 42
ORDER BY created_at DESC;
The INCLUDE clause adds payload columns to the leaf nodes of the B-tree without sorting by them, keeping tree traversal fast while delivering maximum throughput. When creating composite indexes (A, B, C), column order is critical. PostgreSQL can use the index for queries filtering by:
  • (A)
  • (A, B)
  • (A, B, C)
It cannot effectively use the index for filtering by (B) or (C) alone.
Sql
-- Good index ordering: High cardinality column first, equality before ranges
CREATE INDEX idx_users_org_role_created 
ON users (org_id, role, created_at);
Let's optimize a real production query on a table of 4,200,000 event records.
Sql
SELECT event_type, payload->>'action' AS action, created_at
FROM event_stream
WHERE customer_id = 8941
  AND created_at >= NOW() - INTERVAL '7 days'
ORDER BY created_at DESC
LIMIT 20;
Text
Limit  (cost=89432.10..89432.15 rows=20 width=72) (actual time=482.110..482.122 rows=20 loops=1)
  Buffers: shared read=38412 hit=120
  ->  Sort  (cost=89432.10..89435.50 rows=1360 width=72) (actual time=482.108..482.115 rows=20 loops=1)
        Sort Key: created_at DESC
        Sort Method: top-N heapsort  Memory: 28kB
        ->  Seq Scan on event_stream  (cost=0.00..89390.00 rows=1360 width=72) (actual time=24.120..478.430 rows=1410 loops=1)
              Filter: ((customer_id = 8941) AND (created_at >= (now() - '7 days'::interval)))
              Rows Removed by Filter: 4198590
              Buffers: shared read=38412 hit=120
Planning Time: 0.210 ms
Execution Time: 482.350 ms
Diagnosis:
  • Full Seq Scan: Read 4,198,590 rows only to discard them.
  • I/O Footprint: Read 38,412 pages (~300MB) from disk.
  • Latency: 482ms, causing thread starvation under concurrent traffic.
We apply a composite index matching our equality condition first (customer_id), our range/sort condition second (created_at DESC), and include the necessary columns:
Sql
CREATE INDEX CONCURRENTLY idx_event_stream_customer_recent 
ON event_stream (customer_id, created_at DESC) 
INCLUDE (event_type, payload);
[!NOTE] Always use CREATE INDEX CONCURRENTLY in production environments. Standard index creation locks the table against writes (SHARE lock), whereas concurrent builds allow ongoing INSERT, UPDATE, and DELETE transactions.
Text
Limit  (cost=0.56..2.85 rows=20 width=72) (actual time=0.042..0.065 rows=20 loops=1)
  Buffers: shared hit=4
  ->  Index Only Scan using idx_event_stream_customer_recent on event_stream  (cost=0.56..155.80 rows=1360 width=72) (actual time=0.040..0.060 rows=20 loops=1)
        Index Cond: ((customer_id = 8941) AND (created_at >= (now() - '7 days'::interval)))
        Buffers: shared hit=4
Planning Time: 0.120 ms
Execution Time: 0.088 ms
  • Execution Time: Dropped from 482.35ms to 0.088ms (5,480x faster).
  • Buffer I/O: Reduced from 38,412 pages read to 4 shared hits in RAM.
  • Scan Type: Promoted from Seq Scan to zero-heap Index Only Scan.
When you write WHERE LOWER(email) = 'user@example.com', a standard index on email is completely ignored!
Sql
-- WRONG: Forces a Seq Scan across all rows
SELECT * FROM users WHERE LOWER(email) = 'dev@example.com';

-- FIX: Create an Expression Index
CREATE INDEX idx_users_lower_email ON users (LOWER(email));
LIMIT 20 OFFSET 50000 forces the database to scan and discard 50,000 rows before returning 20. Fix: Keyset (Cursor-Based) Pagination:
Sql
-- Fast O(1) seek using index:
SELECT id, title, created_at 
FROM posts 
WHERE created_at < '2026-10-31T12:00:00Z' 
ORDER BY created_at DESC 
LIMIT 20;
PostgreSQL does not automatically index foreign keys! When you delete a parent row, PostgreSQL must perform a Seq Scan on the child table to check referential integrity constraints.
Sql
-- Always index foreign key columns explicitly:
CREATE INDEX idx_order_items_order_id ON order_items (order_id);
You cannot optimize what you do not measure. Enable the pg_stat_statements extension to track slow queries across your entire database:
Sql
-- Check top 5 most time-consuming queries
SELECT 
    round(total_exec_time::numeric, 2) AS total_time_ms,
    calls,
    round(mean_exec_time::numeric, 2) AS avg_time_ms,
    round((100 * total_exec_time / sum(total_exec_time) OVER ())::numeric, 2) AS percentage,
    query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 5;
Optimizing PostgreSQL performance is an engineering discipline, not guesswork:
  1. Profile First: Use EXPLAIN (ANALYZE, BUFFERS) to locate the exact bottleneck (disk reads vs CPU sort).
  2. Select the Right Index: Match the data shape to the index type (B-Tree for ranges/equality, GIN for JSONB/arrays, BRIN for time series).
  3. Use Partial and Covering Indexes: Reduce index size and achieve zero-heap Index Only Scans.
  4. Monitor Continually: Leverage pg_stat_statements to catch slow queries before your users do.