Tuning Queries Against a Workload
Evaluate a candidate index using representative reads and writes.
database, postgresql, query tuning, workload, indexes, explainTune the workload, not just a plan
An index helps some access patterns and costs space and write maintenance. Useful tuning begins with a measurable goal, representative data and query parameters, and equivalent results. Include concurrency, cache state, write traffic, and latency distribution rather than trusting one fast run.
SQL illustration
Suppose a disposable events table has tenant_id and created_at; the
application frequently asks for one tenant's time range. A candidate is:
CREATE INDEX events_tenant_time_idx ON events (tenant_id, created_at);
EXPLAIN (ANALYZE, BUFFERS)
SELECT tenant_id, created_at FROM events
WHERE tenant_id = 7
AND created_at >= TIMESTAMP '2026-02-01'
AND created_at < TIMESTAMP '2026-03-01';
No plan or timing is promised: row counts, statistics, indexes, cache,
parameters and PostgreSQL settings affect the result. The candidate's
leading equality and following range are a hypothesis to measure, not a
universal column-order rule. EXPLAIN ANALYZE executes its statement;
even a SELECT can run side-effecting functions or acquire locks. Use an
authorised disposable environment and review the query first.
See the reasoning
Follow the example one step at a time
Compare a proposed index with a baseline rather than assuming improvement. This is a prepared teaching demonstration, not live code execution.
Define the workload
reads: tenant + time range writes: frequent inserts measure: latency + write cost
A useful experiment reflects both read and write traffic and checks correctness.
Compare and decide
Record a baseline and candidate under comparable conditions; inspect actual versus estimated rows, loops and buffer use, then verify identical results. Refresh or inspect statistics when justified. Consider multiple tenant sizes and write-heavy periods, storage and maintenance, regressions, and rollback. Adding indexes indiscriminately or forcing a plan is not a substitute for testing the real workload.
Reflect on the concept
Four fixed questions to reinforce the reasoning. Answers are not saved or scored.
