Improve execution speed by profiling queries, adding the right indexes, rewriting statements, and tuning configuration.
Large table scans, missing indexes, sub-optimal joins, and misconfigured work_mem are the usual culprits. Start by identifying which factor dominates.
Run EXPLAIN ANALYZE
. It returns the execution plan and actual timing so you can see which step consumes the most time.
Use EXPLAIN
for a quick estimate that does not execute the query. Use EXPLAIN ANALYZE
in staging to get real runtimes. Avoid on production unless the query is harmless.
Indexes allow the planner to locate rows quickly instead of scanning the full table. B-tree indexes serve equality and range filters; partial indexes target frequent, selective predicates.
Index columns used in WHERE
, JOIN
, and ORDER BY
clauses that filter many rows down to few. Verify benefit with EXPLAIN
before committing.
Filter early, select only needed columns, and join on indexed keys. Replace SELECT *
with specific fields to reduce I/O.
work_mem
decides in-memory sort/hash size; effective_cache_size
hints at OS cache; random_page_cost
adjusts index vs. seq-scan choice. Tune conservatively and monitor.
EXPLAIN ANALYZE
and inspect slow nodes.work_mem
if sorts spill to disk.Guessing without data: Always profile first.
Selecting entire rows: Use column lists to shrink buffers.
If the plan shows Index Scan
on your index, it is being used. A Seq Scan
indicates it is not.
Disabling enable_seqscan
for a session can push the planner toward an index, but it is better to adjust cost parameters or rewrite the query.
Auto-analyze covers most cases, but heavy bulk loads benefit from a manual ANALYZE
afterward to refresh statistics immediately.