PostgreSQL Query and Operations Tuning

Tune PostgreSQL queries, indexes, JSONB, replication, and autovacuum with diagnostic SQL and verification steps.

Development / Backendpostgresqlquery-optimization
by AgentVoltv1.0.0
Free to sign up · every skill included with AgentVolt Pro

Before & after

Same prompt, same agent — the only difference is the skill.

Prompt“Optimize this slow database query”
Beforegeneric AI agent
I can help you speed up that query. There are a few common things to check — you might be missing indexes, the query plan might be inefficient, or there could be locking issues. I'd recommend running EXPLAIN ANALYZE on the query to see where the time is being spent. Once we understand the bottleneck, we can add indexes or restructure the query. What's the query you're working with? Database size would also help me give better advice.
Afterwith PostgreSQL Query and Operations Tuning
POSTGRES QUERY OPTIMIZATION

QUERY SUBMITTED:
SELECT u.name, p.title, count(c.id)
FROM users u
JOIN posts p ON u.id = p.user_id
LEFT JOIN comments c ON p.id = c.post_id
WHERE created_at > now() - interval '30 days'
GROUP BY u.id, p.id;

EXPLAIN ANALYZE OUTPUT (execution time 4200ms, 850MB peak memory)
Seq Scan on posts p (cost 0..1200000 rows=980000)
Seq Scan on comments c (cost 0..850000 rows=2100000) ← BOTTLENECK
Hash Join

DIAGNOSIS:
1. No index on comments.post_id — every group by triggers table scan
2. No index on created_at filter — scans entire posts table even for 30-day window
3. LEFT JOIN pulls all comments regardless of date window — exploding result set

OPTIMIZATION STEPS (in order):

1. ADD INDEXES (5 min, zero downtime with CONCURRENTLY)
CREATE INDEX CONCURRENTLY idx_comments_post_id ON comments(post_id);
CREATE INDEX CONCURRENTLY idx_posts_created_at ON posts(created_at DESC);
CREATE INDEX CONCURRENTLY idx_posts_user_created ON posts(user_id, created_at) INCLUDE (id);

2. RESTRUCTURE QUERY (push date filter down)
SELECT u.name, p.title, count(c.id)
FROM posts p
JOIN users u ON p.user_id = u.id
LEFT JOIN comments c ON p.id = c.post_id AND c.created_at > now() - interval '30 days'
WHERE p.created_at > now() - interval '30 days'
GROUP BY u.id, p.id;
← Date filter on LEFT JOIN prevents full table scan of all comments

3. DENORMALIZE IF QUERY RUNS 1000x/day
Add posts.comment_count_30d → update via trigger on comment insert/delete
Eliminate the LEFT JOIN entirely in read-heavy scenarios

EXPECTED RESULT: 4200ms → 180ms (23x speedup)
New plan: Index Scan on idx_posts_created_at → Nested Loop Join → Index Scan on idx_comments_post_id

VERIFY: Run ANALYZE posts; ANALYZE comments; then re-run EXPLAIN ANALYZE to confirm

About this skill

A slow PostgreSQL query does not automatically need another index, and replica lag does not automatically mean a network problem. This skill traces the evidence to the bottleneck, proposes the smallest useful change, and supplies SQL to verify the result.

What it does

  • Reads execution plans for row-estimate errors, repeated inner scans, spills, and expensive filtering.
  • Designs composite, partial, expression, and covering indexes around actual query predicates and ordering.
  • Chooses JSONB storage and index operator classes based on the operators the application uses.
  • Diagnoses autovacuum delays using table thresholds, transaction horizons, and freeze age.
  • Separates replication transport lag, replay backlog, and replication-slot WAL retention.
  • Evaluates extensions against deployment restrictions, privileges, upgrade needs, and simpler built-in alternatives.

What you get

A focused diagnosis with supporting evidence, diagnostic SQL, a proposed change, and explicit validation and rollback steps. When evidence is missing, you get a labeled provisional recommendation and the smallest useful collection request.

Best for

Backend engineers and database operators troubleshooting PostgreSQL workloads, reviewing index changes, or maintaining replication and vacuum health.

SKILL.md preview

SKILL.md
---
name: postgresql-query-and-operations-tuning
description: Diagnose PostgreSQL performance and operations using execution plans, workload statistics, JSONB operator semantics, vacuum horizons, and replication positions. Produce targeted changes with validation and rollback steps. Use when the user says "this Postgres query is slow", "explain this execution plan", "which index should I add", "my JSONB filter keeps scanning everything", "my replica keeps falling behind", "autovacuum is not keeping up", or "should we install this extension".
---

# PostgreSQL Query and Operations Tuning

… (sign up to view the full skill)
Sign up to view, copy, and install the full skill

Featured in

More development skills

View all Development skills →