Log in·Sign up
BestRelay

Back to the Journal

A Second Review Makes SQL Tuning More Reliable

A convincing SQL rewrite can still return the wrong rows. A plausible index can make one query faster while increasing write costs across the application. A second opinion helps when it challenges assumptions and proposes tests. This walkthrough uses a PostgreSQL order dashboard to turn two model reviews into one measurable decision.

First, define the result before changing SQL

Suppose a dashboard needs the latest 100 paid orders for one tenant, restricted to the past 30 days. Each order must contain at least one item. The existing query joins orders to order items, removes duplicate orders, sorts by creation time, and limits the result.

Write down the contract before asking for suggestions: one row per order, tenant isolation, the exact time boundary, and the required output columns. Define a stable ordering using creation time followed by the unique order identifier. Without that tie breaker, equally recent orders can change places between executions, making comparisons misleading.

Next, capture evidence from a representative execution

Choose a tenant with realistic volume and a fixed cutoff timestamp. Capture an actual execution plan with runtime and buffer information. In PostgreSQL, collecting actual execution statistics runs the statement, so use a suitable environment and account for the load.

Look for estimated row counts that differ substantially from actual counts, expensive sorting, repeated inner operations, and large intermediate results. Record total duration and rows returned. Compare repeated executions under similar cache conditions. One fast run after data enters memory does not establish a reliable improvement.

Give the first reviewer a bounded problem

Provide the first model with the query, table definitions, existing indexes, approximate table sizes, and the execution plan. Remove customer data and secrets. Ask it to identify the dominant cost, explain the evidence, and propose one change with a correctness argument.

For this example, a useful hypothesis is that joining every matching item creates duplicate order rows that must later be removed. If the dashboard only needs to establish that an item exists, an existence condition may express the requirement more directly. Treat that as a candidate until measurement supports it.

Ask the second reviewer to challenge equivalence

Give the second model the original query, the proposed rewrite, and the same evidence. Ask it to find conditions under which the results differ. Direct its attention to duplicate handling, nullable columns, join predicates, time boundaries, and the interaction between sorting and limiting.

An existence condition preserves this example’s intent only if item columns are unnecessary and every relevant item filter remains inside that condition. If the original query calculates item totals or deliberately returns multiple rows per order, the rewrite needs a different justification. Two agreeing answers provide less assurance than a specific objection that you can test.

BestRelay can support this workflow with Claude Sonnet 5.5 for the initial review and GPT-6 Astra for the challenge. Its quality-first relay forwards each request to the official model named in it, without substitution. It works with Claude Code, Codex, Gemini CLI, and any OpenAI SDK. Create a BestRelay account to try the two-review workflow. Billing follows provider-reported token counts on a pay-as-you-go basis, with cache reads and writes priced separately; members also earn referral commission when invited users top up.

Test one index against the revised query

After checking the rewrite, consider an orders index beginning with tenant and payment status, followed by the creation timestamp and order identifier. That arrangement may support equality filters followed by the time range and requested ordering. An index on the item table’s order reference may help the existence check.

Inspect existing indexes first. The planner’s choice depends on selectivity, statistics, table size, and expected access costs. Ask both reviewers to explain the proposed index’s storage and write overhead, then test the smallest justified change.

Accept the change only after independent checks

Compare complete ordered results against the original using a consistent database snapshot. Include orders with several items, orders without items, equal timestamps, and rows at the cutoff boundary. Then compare execution plans and repeated timings across tenants with different volumes.

Accept the change when it preserves the contract and improves the workload you measured. Record the evidence and monitor after deployment. The second opinion earns its place by producing a sharper test and a decision another engineer can review.

Want to try the models discussed here? Sign up