Careeroza
Optimization Techniques
Query-level
- Select only the columns you need; avoid
SELECT *. - Filter early with
WHERE, before joins and grouping. - Prefer
EXISTSoverIN/COUNT(*) > 0to test for existence. - Use
UNION ALLinstead ofUNIONwhen 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 20instead of a hugeOFFSET.
Schema-level
- Index foreign keys and the columns in frequent
WHERE/JOIN/ORDER BYclauses. - 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
- Measure: find the slowest/most frequent queries (slow query log,
pg_stat_statements, Query Store). - Explain: read the plan, find the expensive step.
- Change one thing: rewrite, add an index, update statistics.
- Re-measure with realistic data volumes, and check that writes did not get slower.