PostgreSQL Query Optimization: A Practical Guide for Backend Engineers
Slow database queries are one of the most common causes of poor application performance. A query that runs fine on a development dataset of a few hundred rows can grind production to a halt when the table reaches millions of records. PostgreSQL gives you powerful diagnostic tools, a flexible indexing system, and a cost-based query planner — but you need to know how to read and act on what they tell you.
This guide walks through a systematic process: read the execution plan, spot the bottleneck, choose the right fix, and verify the improvement. The examples use illustrative data and are designed to teach the pattern, not to be copied verbatim into production without review.
> [!NOTE] > All SQL examples in this guide are illustrative. Test them in a staging environment against your actual schema and workload before applying to production.
---
1. Understanding the Query Planner
PostgreSQL's query planner is a cost-based optimizer. It inspects table statistics — row counts, value distributions, correlations — stored in pg_statistic and exposed through pg_stats. It then estimates the cheapest execution plan from all the strategies it considers.
Three concepts matter most:
| Concept | What it means | |---|---| | Cost | An arbitrary planner unit (not milliseconds). Lower is faster relative to other plans. | | Rows | Planner's estimated row count at each node. Mismatches with actual rows point to stale statistics. | | Width | Estimated average row size in bytes. Affects sort and hash memory. |
The planner's statistics grow stale when large batches of rows are inserted or deleted without running ANALYZE. Autovacuum handles this automatically on most tables, but heavily written tables may need a tighter autovacuum_analyze_scale_factor setting.
---
2. Reading EXPLAIN ANALYZE
EXPLAIN ANALYZE executes the query and returns actual run-time measurements alongside the planner's estimates.
-- Illustrative example: order lookup for a wholesale distribution platform
EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)
SELECT o.id, o.created_at, c.name AS customer_name, o.total_amount
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE o.status = 'pending'
AND o.created_at >= NOW() - INTERVAL '7 days'
ORDER BY o.created_at DESC
LIMIT 50;
A condensed version of what you might see:
Limit (cost=1842.33..1842.46 rows=50 width=48)
(actual time=234.112..234.127 rows=50 loops=1)
-> Sort (cost=1842.33..1872.21 rows=11951 width=48)
(actual time=234.108..234.116 rows=50 loops=1)
Sort Key: o.created_at DESC
Sort Method: top-N heapsort Memory: 32kB
-> Hash Join (cost=312.00..1534.70 rows=11951 width=48)
(actual time=12.441..221.355 rows=12048 loops=1)
Hash Cond: (o.customer_id = c.id)
-> Seq Scan on orders o
(cost=0.00..1189.60 rows=11951 width=36)
(actual time=0.025..198.442 rows=12048 loops=1)
Filter: ((status = 'pending') AND
(created_at >= (now() - '7 days'::interval)))
Rows Removed by Filter: 28952
-> Hash on customers c
(cost=199.00..199.00 rows=9000 width=20)
(actual time=12.390..12.390 rows=9000 loops=1)
Planning Time: 1.231 ms
Execution Time: 234.198 ms
What to look for:
- Seq Scan on a large table — PostgreSQL read every row in
ordersand discarded 28,952 of them. This is the bottleneck. - Rows Removed by Filter — high number relative to rows returned signals a missing index.
- Planner estimate vs. actual rows — the planner estimated 11,951 rows; actual was 12,048. Close enough here, but a 10× or 100× mismatch means stale statistics.
- Sort Method: external merge — if you see this instead of heapsort, the sort spilled to disk. Increase
work_mem.
---
3. The Four Index Types You Actually Use
3.1 B-tree (the default)
B-tree indexes cover equality (=), range (<, >, BETWEEN), and ORDER BY. They handle most OLTP workloads.
-- Fix the sequential scan above: index on status + created_at
-- (illustrative — validate column cardinality on your data first)
CREATE INDEX CONCURRENTLY idx_orders_status_created
ON orders (status, created_at DESC)
WHERE status IN ('pending', 'processing'); -- partial index to keep it small
CONCURRENTLY lets PostgreSQL build the index without locking writes — essential on a live table.
Column order matters: put the equality column (status) first, the range/sort column (created_at) second. This lets the planner use the index for both the filter and the ORDER BY, often eliminating the sort node entirely.
3.2 GIN (Generalized Inverted Index)
GIN excels at multi-value data: arrays, JSONB, and full-text search vectors.
-- Index JSONB attributes for a product catalog
CREATE INDEX CONCURRENTLY idx_products_attributes
ON products USING GIN (attributes jsonb_path_ops);
-- Query can now use the index instead of scanning the whole table
SELECT * FROM products
WHERE attributes @> '{"category": "electronics", "in_stock": true}';
> [!TIP] > Use jsonb_path_ops (not the default jsonb_ops) when you only need @> containment checks. It produces a smaller, faster index.
3.3 BRIN (Block Range INdex)
BRIN is for physically ordered, append-only data like time-series events or log tables. The index is tiny (a few kilobytes for a billion-row table) because it stores only min/max values per block range.
-- Illustrative: BRIN on a high-volume delivery_events table
-- Only effective when rows are inserted in roughly timestamp order
CREATE INDEX CONCURRENTLY idx_delivery_events_brin
ON delivery_events USING BRIN (event_time)
WITH (pages_per_range = 128);
3.4 Covering Indexes (INCLUDE)
An INCLUDE clause adds extra columns to the index without making them part of the key. The planner can satisfy a query entirely from the index (an index-only scan) without touching the heap.
-- Include columns needed by the SELECT so the heap is never touched
CREATE INDEX CONCURRENTLY idx_orders_cover
ON orders (status, created_at DESC)
INCLUDE (customer_id, total_amount)
WHERE status IN ('pending', 'processing');
After adding this index, re-run EXPLAIN ANALYZE and look for Index Only Scan and Heap Fetches: 0.
---
4. Diagnosing Specific Anti-Patterns
4.1 Non-sargable predicates
A predicate is sargable (Search ARGument ABLE) if the planner can use an index to satisfy it. Function calls on the indexed column break sargability.
-- ❌ Non-sargable: wrapping the column prevents index use
SELECT * FROM invoices WHERE DATE(issued_at) = '2026-11-01';
-- ✅ Sargable: range on the column itself
SELECT * FROM invoices
WHERE issued_at >= '2026-11-01'
AND issued_at < '2026-11-02';
The same applies to LOWER(email) = '[email protected]' — solve it with a functional index or by storing the value normalized.
-- Functional index for case-insensitive email lookup
CREATE INDEX idx_customers_email_lower
ON customers (LOWER(email));
-- Now this query is sargable against that index
SELECT * FROM customers WHERE LOWER(email) = '[email protected]';
4.2 Implicit type casts
If the column is INTEGER and your parameter is a string, PostgreSQL casts every column value at run time, defeating the index.
-- ❌ Triggers implicit cast if branch_id is INTEGER
SELECT * FROM inventory WHERE branch_id = '5';
-- ✅ Match the column type
SELECT * FROM inventory WHERE branch_id = 5;
Always use typed bind parameters in your application driver (e.g., pass an integer from your ORM, not a stringified value).
4.3 N+1 queries
An N+1 pattern executes one query per row of a parent result — common in ORMs. The fix is a single JOIN or a WHERE id = ANY($1) batch fetch.
-- ❌ N+1: for each order, one round-trip to fetch the customer
-- (shown as pseudocode, not valid SQL)
-- for order in orders: SELECT * FROM customers WHERE id = order.customer_id
-- ✅ One query fetches everything
SELECT o.id, o.total_amount, c.name, c.phone
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE o.id = ANY(ARRAY[101, 102, 103, 104]); -- batch of IDs from application
4.4 Expensive aggregations on unindexed columns
-- ❌ Full table scan for revenue report
SELECT branch_id, SUM(total_amount) AS revenue
FROM orders
WHERE created_at BETWEEN '2026-10-01' AND '2026-10-31'
GROUP BY branch_id;
-- After creating a composite index on (created_at, branch_id, total_amount)
-- the planner can use an index-only scan for the entire aggregation
CREATE INDEX CONCURRENTLY idx_orders_report
ON orders (created_at, branch_id)
INCLUDE (total_amount);
---
5. Planner Configuration Knobs
A few server parameters have an outsized impact on plan quality and stability.
5.1 work_mem
work_mem is the memory budget per sort or hash operation, per connection. The default (4 MB) is often too low for analytical queries.
-- Set for the current session only (safest approach)
SET work_mem = '64MB';
-- Then run your expensive analytical query
EXPLAIN (ANALYZE, BUFFERS)
SELECT ...;
> [!WARNING] > Setting work_mem globally in postgresql.conf multiplies by active connections × sorts per query. On a server with 200 connections each running a 3-sort query, 64 MB × 200 × 3 = 38.4 GB of RAM can be consumed. Use SET LOCAL inside transactions or connection-level settings for heavy queries.
5.2 Statistics target
The planner samples a fraction of each column's values to build its histogram. The default default_statistics_target = 100 can be too coarse for skewed distributions.
-- Increase statistics for a column with high cardinality or skewed distribution
ALTER TABLE orders ALTER COLUMN customer_id SET STATISTICS 500;
-- Then refresh the statistics
ANALYZE orders;
5.3 enable_* toggles
If the planner consistently chooses a bad plan (confirmed by comparing EXPLAIN ANALYZE costs), you can nudge it without changing schema by toggling strategy flags:
-- Disable sequential scans to force the planner to consider indexes
-- (use in a session-level diagnostic, never as a permanent global setting)
SET enable_seqscan = off;
EXPLAIN ANALYZE SELECT ...;
SET enable_seqscan = on;
This is a diagnostic tool, not a production fix. If the planner avoids an index on its own, the statistics or index design is usually at fault.
---
6. Identifying Slow Queries in Production
6.1 pg_stat_statements
Enable the pg_stat_statements extension to aggregate query statistics across all executions:
-- Enable once per database (requires superuser or pg_monitor role)
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
-- Find the top 10 queries by total execution time
SELECT
LEFT(query, 120) AS query_preview,
calls,
ROUND(total_exec_time::numeric, 2) AS total_ms,
ROUND(mean_exec_time::numeric, 2) AS mean_ms,
ROUND(stddev_exec_time::numeric, 2) AS stddev_ms,
rows
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;
The stddev_ms column reveals queries with inconsistent latency — often caused by cache misses on the first execution after a cold buffer cache.
6.2 auto_explain
The auto_explain module logs the execution plan of any query exceeding a threshold, without changing application code:
# In postgresql.conf (illustrative — tune threshold to your workload)
shared_preload_libraries = 'auto_explain'
auto_explain.log_min_duration = 500 # ms
auto_explain.log_analyze = on
auto_explain.log_buffers = on
auto_explain.log_format = text
Restart PostgreSQL, then check the server log for plans from real production queries.
---
7. A Repeatable Optimization Workflow
1. Identify → pg_stat_statements: sort by total_exec_time
2. Isolate → Run the specific query with EXPLAIN (ANALYZE, BUFFERS)
3. Diagnose → Look for Seq Scan on large tables, high Rows Removed, sort spills
4. Hypothesize → Choose the right fix: index, query rewrite, statistics, work_mem
5. Test → Apply change in a staging environment; re-run EXPLAIN ANALYZE
6. Measure → Compare planning time + execution time before and after
7. Deploy → Use CONCURRENTLY for index creation; monitor pg_stat_statements after
> [!IMPORTANT] > Always measure before and after. The planner's cost estimate can mislead you — only wall-clock Execution Time from EXPLAIN ANALYZE on realistic data confirms an improvement. Avoid drawing conclusions from query plans on small or synthetic datasets.
---
8. Index Maintenance
Indexes accumulate dead tuples (bloat) from updates and deletes. Autovacuum reclaims heap space but index bloat requires either VACUUM (which reclaims space for reuse) or REINDEX CONCURRENTLY (which rebuilds the index without a write lock).
-- Check index bloat using the pgstattuple extension (illustrative)
CREATE EXTENSION IF NOT EXISTS pgstattuple;
SELECT
schemaname,
indexrelname,
pg_size_pretty(pg_relation_size(indexrelid)) AS index_size,
idx_scan,
idx_tup_read,
idx_tup_fetch
FROM pg_stat_user_indexes
ORDER BY pg_relation_size(indexrelid) DESC
LIMIT 20;
-- Rebuild a bloated index without locking writes
REINDEX INDEX CONCURRENTLY idx_orders_status_created;
Also prune unused indexes: every index you add slows down INSERT, UPDATE, and DELETE. An index with idx_scan = 0 after weeks of production traffic is a candidate for removal.
-- Find unused indexes (run after the system has been live for at least a week)
SELECT
schemaname,
relname AS table_name,
indexrelname AS index_name,
pg_size_pretty(pg_relation_size(indexrelid)) AS size,
idx_scan
FROM pg_stat_user_indexes
WHERE idx_scan = 0
AND indexrelname NOT LIKE '%_pkey' -- keep primary keys
ORDER BY pg_relation_size(indexrelid) DESC;
---
Conclusion
Query optimization in PostgreSQL is an iterative process: measure, understand the execution plan, apply the smallest change that addresses the bottleneck, and verify. The techniques in this guide — reading EXPLAIN ANALYZE, choosing the right index type, rewriting non-sargable predicates, tuning work_mem, and using pg_stat_statements for production visibility — cover the majority of performance issues you will encounter in business applications.
The most important discipline is to benchmark against realistic data volumes. A synthetic test on 10,000 rows rarely predicts behavior on 10 million, because the planner's decisions shift as table sizes, row widths, and value distributions change.
---
Need help profiling and optimizing a PostgreSQL-backed system? Dragonfly Soft's backend engineering team has worked on high-traffic platforms across wholesale distribution, e-commerce, and logistics in Syria and the region. We can conduct a database audit, design an indexing strategy, or refactor queries as part of a broader performance engagement.