SQL Query Optimizer

Diagnoses a slow SQL query and returns an optimized rewrite, index plan, and execution-plan reasoning.

// prompt
You are a **senior database administrator and SQL performance engineer** specializing in the database engine given below. Diagnose and optimize the query below, explaining every change so I learn the reasoning — not just the result. ## Context - **Database engine & version:** {{database_engine_and_version}} - **Slow query:** ```sql {{current_query}} ``` - **Relevant schema:** table definitions, row counts, existing indexes — {{schema_and_indexes}} - **Symptom:** {{performance_problem}} - **Goal:** {{target_outcome}} ## How to proceed 1. **Read the plan.** State which EXPLAIN/ANALYZE output you need; infer likely bottlenecks (scans, bad join order, spills, missing/unused indexes, non-sargable predicates, N+1). 2. **Find the root cause.** Identify the single biggest cost driver and why the planner chose it. 3. **Rewrite the query.** Provide a corrected version that is logically equivalent and returns identical results. 4. **Propose indexes.** Give exact `CREATE INDEX` statements with column order rationale; flag any redundant or write-penalizing indexes. 5. **Note schema/config options** only if they materially help (partitioning, data types, statistics, denormalization) — keep these as suggestions. ## Deliver in this format - **Diagnosis** — root cause in 2-4 sentences. - **Optimized query** — a single SQL block, commented at the changed lines. - **Index recommendations** — `CREATE INDEX` statements + one line each on why. - **Why it's faster** — map each change to the cost it removes; give a rough before/after estimate. - **Trade-offs & risks** — write overhead, storage, edge cases to verify. - **Validation step** — the exact command I should run to confirm the improvement. Constraints: stay strictly within that engine's dialect and supported features. If the provided schema or plan is insufficient to be certain, list the specific information you need before committing to a recommendation. Do not invent table or column names.
Fill in the variables

Example run

Generated by Claude Opus 5.5 on November 25, 2026

Inputs used

Database engine and version
PostgreSQL 15.4 (Amazon RDS, db.r6g.xlarge)
Current query
-- Dashboard widget: "Top customers by revenue, last 30 days" -- Runs every 10s for up to 50 concurrent analysts refreshing the admin panel. SELECT c.customer_id, c.company_name, c.region, COUNT(DISTINCT o.order_id) AS order_count, SUM(oi.quantity * oi.unit_price) AS gross_revenue, SUM(oi.quantity * oi.unit_price * (1 - oi.discount)) AS net_revenue, MAX(o.order_date) AS last_order_date FROM customers c JOIN orders o ON o.customer_id = c.customer_id JOIN order_items oi ON oi.order_id = o.order_id WHERE -- non-sargable: wraps indexed column in a function DATE_TRUNC('day', o.order_date) >= DATE_TRUNC('day', NOW() - INTERVAL '30 days') AND ( o.status = 'completed' OR o.status = 'shipped' ) AND c.is_active = true GROUP BY c.customer_id, c.company_name, c.region HAVING SUM(oi.quantity * oi.unit_price) > 500 ORDER BY net_revenue DESC LIMIT 25;
Schema and indexes
-- Row counts as of 2026-11-24 (pg_stat_user_tables.n_live_tup) CREATE TABLE customers ( customer_id BIGINT PRIMARY KEY, company_name TEXT NOT NULL, region TEXT NOT NULL, is_active BOOLEAN NOT NULL DEFAULT true, created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); -- ~185,000 rows CREATE INDEX idx_customers_region ON customers (region); CREATE TABLE orders ( order_id BIGINT PRIMARY KEY, customer_id BIGINT NOT NULL REFERENCES customers(customer_id), order_date TIMESTAMPTZ NOT NULL, status TEXT NOT NULL, -- 'pending','completed','shipped','cancelled','refunded' warehouse_id INT NOT NULL ); -- ~4,200,000 rows, growing ~15k/day CREATE INDEX idx_orders_customer_id ON orders (customer_id); CREATE INDEX idx_orders_order_date ON orders (order_date); -- note: no composite index covering (order_date, status) or (customer_id, order_date) CREATE TABLE order_items ( order_item_id BIGINT PRIMARY KEY, order_id BIGINT NOT NULL REFERENCES orders(order_id), product_id BIGINT NOT NULL, quantity INT NOT NULL, unit_price NUMERIC(10,2) NOT NULL, discount NUMERIC(4,3) NOT NULL DEFAULT 0 ); -- ~18,600,000 rows (avg ~4.4 items per order) CREATE INDEX idx_order_items_order_id ON order_items (order_id); CREATE INDEX idx_order_items_product_id ON order_items (product_id); -- autovacuum: default settings, last ANALYZE on orders was 6 days ago -- work_mem = 64MB, shared_buffers = 8GB, effective_cache_size = 24GB
Performance problem
EXPLAIN ANALYZE shows ~7.8s average runtime; planner picks a Seq Scan on orders (4.2M rows, cost~210000) feeding a Hash Join against order_items instead of using idx_orders_order_date, because DATE_TRUNC() on order_date defeats the index; also a sort spills to disk (Sort Method: external merge, ~140MB) before the LIMIT 25.
Target outcome
Sub-300ms p95 execution time so the dashboard widget can safely auto-refresh every 10s for ~50 concurrent analysts without saturating the replica's I/O.

Optimizing the "Top customers by revenue, last 30 days" query (PostgreSQL 15.4)

What I need before committing fully

My recommendations rest on the schema, row counts and plan symptoms you gave. Please send the following so I can confirm the numbers.

  1. The full plan, not a summary:
    EXPLAIN (ANALYZE, BUFFERS, VERBOSE, SETTINGS) <original query>;
    
    I need per-node actual rows, loops, Buffers: shared hit/read and temp read/written. Those show which node really owns the 7.8 s.
  2. How many rows are in the window:
    SELECT status, count(*) FROM orders
    WHERE order_date >= date_trunc('day', now() - interval '30 days')
    GROUP BY status;
    
  3. Session timezone and stats:
    SHOW timezone;
    SELECT attname, n_distinct, correlation FROM pg_stats
    WHERE tablename = 'orders' AND attname IN ('order_id','order_date','status');
    
    This tells me whether order_id tracks time and how status is distributed.
  4. Where it runs: does the dashboard hit the read replica? Indexes and materialized views must be created on the primary.
  5. How often orders change status after insert. This decides the HOT-update cost of the partial index below.

My working assumption: ~15k orders/day means ~450k orders in the window and ~300k after the status filter. At 4.4 items per order, that is roughly 1.3–2M order_items rows to aggregate.


Diagnosis

The non-sargable DATE_TRUNC is real, but it is probably not the largest cost.

  • The hash join is the main cost. Postgres builds a hash on the filtered orders and then probes it with a sequential scan of all 18.6M order_items rows. That is about 4x the row volume of the orders seq scan.
  • The 140 MB spill is not the final ORDER BY … LIMIT sort. That sort works on a few thousand aggregated rows and would use a cheap top-N heapsort. The spill comes from COUNT(DISTINCT o.order_id). PG15 cannot hash-aggregate DISTINCT aggregates, so it sorts the whole ~1.5M-row join output by customer before a GroupAggregate. 1.5M rows at ~100 bytes each is about 140 MB, which matches your number.
  • Even a perfect plan has a floor. It still aggregates ~1.5M rows per run, roughly 0.5–1 s of CPU.
  • The load maths does not work. 50 analysts refreshing every 10 s is about 5 queries/s. On a 4-vCPU r6g.xlarge, that is beyond what live execution can sustain at sub-300 ms p95.

The fix therefore has two layers:

  • (a) Make the query cheap: sargable predicate, pre-aggregation, covering indexes.
  • (b) Stop recomputing the same answer 5 times a second (see the schema section).

Optimized query

-- Logically equivalent rewrite. CTEs referenced once are inlined in PG12+,
-- so this is readability, not an optimization fence.
WITH recent_orders AS (
    SELECT o.order_id, o.customer_id, o.order_date
    FROM orders o
    WHERE
        -- CHANGED: sargable. The bound is midnight 30 days ago, so
        -- date_trunc('day', x) >= D  <=>  x >= D. Same session-TZ semantics.
        o.order_date >= date_trunc('day', now() - interval '30 days')
        -- CHANGED: OR -> IN. Same meaning; becomes a single = ANY(array)
        -- index condition and matches the partial index predicate verbatim.
        AND o.status IN ('completed', 'shipped')
),
order_totals AS (
    -- NEW STEP: collapse items to one row per order BEFORE grouping by customer.
    -- Removes the need for COUNT(DISTINCT), and with it the 140MB sort.
    SELECT ro.order_id,
           ro.customer_id,
           ro.order_date,
           SUM(oi.quantity * oi.unit_price)                     AS gross,
           SUM(oi.quantity * oi.unit_price * (1 - oi.discount)) AS net
    FROM recent_orders ro
    JOIN order_items oi ON oi.order_id = ro.order_id  -- inner join: orders with no items stay excluded, as before
    GROUP BY ro.order_id, ro.customer_id, ro.order_date
),
customer_totals AS (
    SELECT customer_id,
           COUNT(*)        AS order_count,      -- CHANGED: one row per order now, so COUNT(*) = COUNT(DISTINCT order_id)
           SUM(gross)      AS gross_revenue,    -- NUMERIC is exact: sum of per-order sums = original sum
           SUM(net)        AS net_revenue,
           MAX(order_date) AS last_order_date
    FROM order_totals
    GROUP BY customer_id                        -- CHANGED: hashable (no DISTINCT aggregate), fits in hash_mem
    HAVING SUM(gross) > 500                     -- same filter; depends only on customer sums
)
SELECT c.customer_id,
       c.company_name,
       c.region,
       ct.order_count,
       ct.gross_revenue,
       ct.net_revenue,
       ct.last_order_date
FROM customer_totals ct
JOIN customers c ON c.customer_id = ct.customer_id   -- CHANGED: join customers AFTER aggregation (1:1 on PK)
WHERE c.is_active = true
ORDER BY ct.net_revenue DESC,
         c.customer_id                               -- ADDED: deterministic tie-break (see risks)
LIMIT 25;

Why each change preserves results:

Change Why results are unchanged
x >= date_trunc('day', …) The right-hand side is already a midnight boundary. Truncation is monotonic and never increases a value, so the two predicates select exactly the same rows.
Pre-aggregation Each order belongs to exactly one customer. NUMERIC addition is exact, so regrouping gives identical sums, including scale. With float this would not be guaranteed.
Moving the customers join after HAVING customer_id is the PK and the FK is NOT NULL, so the join neither multiplies nor drops rows. is_active and HAVING are independent filters on the same customer, so their order does not matter. company_name and region are functionally dependent on the PK.

Index recommendations

Build both on the primary with CONCURRENTLY so writes are not blocked.

-- 1. Orders: range scan on date, restricted to the two statuses, covering the join keys.
CREATE INDEX CONCURRENTLY idx_orders_date_completed_shipped
    ON orders (order_date)
    INCLUDE (customer_id, order_id)
    WHERE status IN ('completed', 'shipped');
  • Column choice: order_date leads because it is the range predicate.
  • No status column needed: the partial predicate already fixes status, which also makes the index smaller.
  • Covering: INCLUDE (customer_id, order_id) allows an index-only scan, so the ~300k qualifying orders never touch the heap.
-- 2. Order items: covering index for the per-order lookup.
CREATE INDEX CONCURRENTLY idx_order_items_order_id_covering
    ON order_items (order_id)
    INCLUDE (quantity, unit_price, discount);

-- Then retire the now-redundant index (same leading column; the FK check still uses the new one):
DROP INDEX CONCURRENTLY idx_order_items_order_id;
  • Effect: each joined order becomes an index-only probe that returns all three arithmetic columns. Postgres no longer needs the 18.6M-row seq scan.

Not needed: nothing on customers. At most a few thousand PK lookups, or one 185k-row hash, costs about 10–20 ms. idx_customers_region plays no role in this query.

Possibly redundant: idx_orders_order_date. Keep it unless pg_stat_user_indexes.idx_scan shows nothing else uses it. Other queries may filter by date across all statuses.


Why it's faster

Cost removed Mechanism Rough effect
18.6M-row seq scan of order_items (likely the biggest node) Nested loop or merge join via covering index, ~1.3–2M index tuples, index-only ~3–4 s → ~0.3–0.6 s (cached)
4.2M-row seq scan of orders Index-only range scan over ~300k entries in the partial index ~1 s → ~20–50 ms
140 MB external merge sort (COUNT DISTINCT → GroupAggregate) Pre-aggregation gives two HashAggregates. ~300k groups fit in work_mem × hash_mem_multiplier (64 MB × 2 = 128 MB) ~1–2 s plus temp I/O → ~150–300 ms, no disk
customers join on every row Join on aggregated rows only Small, but removes per-row work

Rough estimates:

  • Before: ~7.8 s.
  • After the rewrite and indexes: ~0.5–1.2 s single-backend, warm cache. Confirm with BUFFERS.

That is a 7–15x improvement, but it will not reliably reach sub-300 ms p95 at 50 concurrent users. The aggregation over ~1.5M rows is irreducible work, and 5 runs per second would consume more than 4 vCPUs.

Getting to the sub-300 ms goal: compute once, read many

Every analyst sees the same answer, so compute it on a schedule instead of per request. The object name below is a suggestion for a new object.

-- On the primary:
CREATE MATERIALIZED VIEW dashboard_top_customers_30d AS
    <optimized query above>;

CREATE UNIQUE INDEX ON dashboard_top_customers_30d (customer_id);  -- required for CONCURRENTLY

-- pg_cron is available on RDS PG15. Second-granularity schedules need pg_cron >= 1.5,
-- so check with: SELECT extversion FROM pg_extension WHERE extname = 'pg_cron';
SELECT cron.schedule(
    'refresh-top-customers',
    '30 seconds',
    $$REFRESH MATERIALIZED VIEW CONCURRENTLY dashboard_top_customers_30d$$
);

-- Dashboard query, served from the replica in well under 1 ms:
SELECT * FROM dashboard_top_customers_30d
ORDER BY net_revenue DESC, customer_id;

Load comparison:

  • Before: 5 heavy queries/s.
  • After: one ~1 s query every 30 s on the primary, plus trivial 25-row reads.

Staleness: freshness becomes "refresh interval + replica lag". Your widget already tolerates up to 10 s of staleness, so ask product whether 30–60 s is acceptable. An app-side cache with a 10–30 s TTL achieves the same effect if you prefer not to add a database object.

Other options I considered

  • Daily rollup table: the window is day-aligned, so you could combine a daily rollup with a live "today" query. But late status changes (pending → completed, completed → refunded) mutate past days, and keeping that correct needs triggers or re-rollups. Use the MV unless it proves insufficient.
  • Monthly partitioning of orders: pruning with now() works at executor startup, but at 4.2M rows the partial index gives most of the benefit. Revisit when the table reaches tens of millions of rows.
  • Statistics: the default autovacuum_analyze_scale_factor = 0.1 means about 420k changed rows before re-ANALYZE, which takes weeks at your growth rate. The settings below also keep the visibility map current, which index-only scans depend on. Run them on the primary:
    ALTER TABLE orders      SET (autovacuum_analyze_scale_factor = 0.01,
                                 autovacuum_vacuum_insert_scale_factor = 0.02);
    ALTER TABLE order_items SET (autovacuum_vacuum_insert_scale_factor = 0.02);
    ANALYZE orders; ANALYZE order_items;
    
  • Do not raise work_mem globally. 64 MB × several nodes × 50 sessions can already add up to gigabytes. If needed, set it per role or per session instead.

Trade-offs and risks

Write and storage overhead

  • The order_items covering index loses deduplication. B-tree deduplication is disabled for indexes with INCLUDE. Expect roughly 0.8–1 GB versus the current deduplicated index (likely ~0.3 GB). Each insert into order_items pays slightly more.
  • The partial orders index affects HOT updates. status appears in its predicate, so a status change can no longer be a HOT update and writes new index entries. If orders flip status often, monitor n_tup_hot_upd in pg_stat_user_tables. The alternative is a plain (order_date) INCLUDE (customer_id, order_id, status) index, which is larger but has no predicate.
  • Index-only scans depend on vacuum. If the visibility map lags, the scans fall back to heap fetches. Watch Heap Fetches: in the plan.

Edge cases to verify

  • Ties at position 25: the original ORDER BY net_revenue DESC was nondeterministic when values tied. The customer_id tie-break returns one of the result sets the original could have returned, but it is now stable. Remove it if you need byte-for-byte plan behaviour, though I would keep it.
  • Timezone: date_trunc on timestamptz uses the session TimeZone, exactly as before. The MV, however, freezes the refresh session's timezone. Make sure the pg_cron job's timezone (usually UTC on RDS) is what the analysts expect.
  • Materialized view refresh: REFRESH … CONCURRENTLY needs the unique index and briefly holds an EXCLUSIVE lock that blocks other refreshes but not readers. A non-concurrent refresh would block readers.
  • Replica: if the refresh query runs long on the primary, nothing changes on the replica. But if the live query keeps running on the replica, long queries combined with hot_standby_feedback can cause primary bloat.

Validation step

1. Equivalence check. This should return 0 rows. Run both in the same session, at the same moment, with the same timezone:

(<original query>  EXCEPT ALL <optimized query>)
UNION ALL
(<optimized query> EXCEPT ALL <original query>);

2. Plan check. Look for these signs:

  • Index Only Scan using idx_orders_date_completed_shipped
  • Index Only Scan using idx_order_items_order_id_covering with low Heap Fetches
  • HashAggregate with no Disk Usage
  • no external merge
EXPLAIN (ANALYZE, BUFFERS, SETTINGS) <optimized query>;

3. p95 under realistic concurrency. Run this from a client host against the replica:

# Put the optimized query (or the MV SELECT) in widget.sql, then:
pgbench -n -f widget.sql -c 50 -j 4 -T 120 --rate=5 -l --log-prefix=widget \
        -h <replica-endpoint> -U <user> <db>

# p95 latency in ms (column 3 of the pgbench log is latency in µs):
cat widget.* | awk '{print $3}' | sort -n \
  | awk '{a[NR]=$1} END {print "p95 ms:", a[int(NR*0.95)]/1000}'

Run it twice: once with the live optimized query and once with the materialized view read. Comparing the two shows whether the rewrite alone meets the target on your actual data. My expectation is that it will not at 5 queries/s, and that the materialized view will meet it comfortably.

Related prompts

Programming & Development

Algorithm Design Expert

Designs, analyzes, and optimizes algorithms with multiple approaches, Big-O complexity analysis, production code, and tests.

{} 9 vars
Programming & Development

Python Development Specialist

Generates production-ready, fully typed Python code with tests, docstrings, and usage examples to your spec.

{} 6 vars
Programming & Development

JavaScript & React Development Expert

Generates production-grade, typed React and JavaScript code with tests, accessibility, and clear architectural reasoning.

{} 8 vars
Programming & Development

Advanced Debugging Assistant

Diagnoses bugs in your code, pinpoints root causes, and delivers fixed code with prevention tips.

{} 6 vars