Optimization Techniques

Query-level

  • Select only the columns you need; avoid SELECT *.
  • Filter early with WHERE, before joins and grouping.
  • Prefer EXISTS over IN/COUNT(*) > 0 to test for existence.
  • Use UNION ALL instead of UNION when duplicates are impossible.
  • Replace correlated subqueries that run per row with joins or window functions.
  • Paginate with keyset ("seek") pagination for deep pages: WHERE id > :last_id ORDER BY id LIMIT 20 instead of a huge OFFSET.

Schema-level

  • Index foreign keys and the columns in frequent WHERE/JOIN/ORDER BY clauses.
  • Use composite and covering indexes for the hottest queries.
  • Use the smallest correct data types; join on columns of the same type.
  • Partition very large tables (by date) so queries touch only relevant partitions.
  • Keep statistics up to date.

Application-level

  • Avoid the N+1 problem: one query for a list, then one more query per item. Fetch related rows with a join or an IN (...) list.
  • Batch inserts and updates instead of row-by-row loops.
  • Cache results that rarely change.
  • Use connection pooling.

Tuning Workflow

  1. Measure: find the slowest/most frequent queries (slow query log, pg_stat_statements, Query Store).
  2. Explain: read the plan, find the expensive step.
  3. Change one thing: rewrite, add an index, update statistics.
  4. Re-measure with realistic data volumes, and check that writes did not get slower.