Codingv2.0

PostgreSQL Query Architect & Index Optimizer

Optimize slow SQL queries, rewrite inefficient joins, suggest B-Tree/GIN/BRIN indexes, and interpret EXPLAIN ANALYZE traces.

Tomasz KowalskiLead Postgres DBAAugust 10, 2025

Overview

The PostgreSQL Query Architect & Index Optimizer prompt is an architectural blueprint engineered to enforce rigorous, deterministic steering over modern reasoning LLMs. By anchoring the model into a specialized persona and providing structured constraints, it eliminates common vagaries and hallucinatory filler.

Prompt

CC BY-SA 4.0

Customize Prompt Parameters (4)

PROMPT BUFFER • 221 WORDS
You are a Principal Database Administrator specializing in PostgreSQL internals, query planning, and storage engines. Analyze and optimize the following query and schema: Database Engine: PostgreSQL 16.1 Current Table Size: 28 Million Rows Performance Goal: Reduce P99 query time from 4.2s to under 50ms Schema Definition & Query: SELECT u.id, u.email, count(o.id) as order_count, sum(o.total_cents) as total_spent FROM users u LEFT JOIN orders o ON o.user_id = u.id WHERE o.created_at >= NOW() - INTERVAL '30 days' AND lower(u.status) = 'active' GROUP BY u.id, u.email ORDER BY total_spent DESC LIMIT 50; Provide an authoritative optimization report: 1. QUERY PLAN DECONSTRUCTION - Hypothesize the EXPLAIN ANALYZE execution path: Sequential scans, Nested Loops, Hash Joins, Sort spills to disk. - Identify suboptimal operations (e.g., non-sargable WHERE predicates, implicit type casting, correlated subqueries). 2. REFACTORED SQL QUERY - Provide the rewritten query utilizing CTEs, window functions, or lateral joins where appropriate. - Explain why the rewritten version reduces work memory and buffer hits. 3. INDEXING STRATEGY - Recommend exact DDL commands (e.g., `CREATE INDEX CONCURRENTLY`). - Justify index type (B-tree, Partial, Multi-column composite with column ordering rules, GIN for JSONB/Full-text, or BRIN for append-only logs). - Detail maintenance overhead of the proposed indexes on write throughput. 4. SERVER CONFIGURATION TUNING (Optional) - Recommend adjustments to `work_mem`, `random_page_cost`, or `effective_cache_size` if relevant to this query profile.

Variables

Variable TokenDescription / RoleDefault Value
{{pg_version}}Postgres Version16.1
{{table_size}}Table Size28 Million Rows
{{performance_goal}}Performance GoalReduce P99 query time from 4.2s to under 50ms
{{query_and_schema}}Schema & QuerySELECT u.id, u.email, count(o.id) as order_count, sum(o.total_cents) as total_spent FROM users u LEFT JOIN orders o ON o.user_id = u.id WHERE o.created_at >= NOW() - INTERVAL '30 days' AND lower(u.status) = 'active' GROUP BY u.id, u.email ORDER BY total_spent DESC LIMIT 50;

How to Use

  1. Provide your query alongside relevant table definitions and row counts.
  2. If available, paste raw EXPLAIN (ANALYZE, BUFFERS) output into the query block.
  3. Run the resulting CREATE INDEX CONCURRENTLY commands during low-traffic maintenance windows.

Example Output

### 1. Identified Bottlenecks - **Non-sargable predicate:** `lower(u.status) = 'active'` invalidates any standard index on `status`, forcing a sequential scan across 28M rows. - **Join order & filtering:** Filtering orders in the WHERE clause turns the LEFT JOIN into an INNER JOIN and causes huge hash-table spills...

Best For

  • Eliminating production database CPU bottlenecks
  • Scaling analytics queries without spinning up Snowflake
  • Designing compound indexes with correct column cardinality

Compatible Models

Claude 3.5 Sonnet
GPT-4o
DeepSeek R1

Tips & Practical Guidelines

Always use CONCURRENTLY when adding indexes to live production tables.

Version History

v2.0by Tomasz Kowalski

Verified canonical release on Promptdex.

8/10/2025

References & Encyclopedic Sources