Back to the journal

Backend engineering / 2 MIN READ

Query tuning starts with the question

The fastest query is unhelpful if it computes the wrong thing.

Sai Sri Harsha Guddati ·

My earlier systems-engineering work included PostgreSQL and MSSQL query tuning. The habit I want to preserve from that work is simple: understand the query's purpose before trying to make its execution faster.

A slow endpoint can invite a quick index change. Sometimes that helps. Sometimes the query is doing more work than the product actually needs.

Write down the intended result

An illustrative dashboard may request all historical records when it displays only the most recent page. Another endpoint may join a large table only to confirm that one related record exists. A third may repeat the same lookup for every item.

Before choosing an optimization, I would define the exact result and inspect the path that produces it. Pagination, filtering, and aggregation choices can change the amount of work more substantially than a local implementation tweak.

Correctness remains the first constraint. An index does not rescue an incorrect join.

Inspect the plan

PostgreSQL's EXPLAIN documentation describes how to inspect the planner's chosen execution plan, including estimates and actual execution details when requested. That information helps replace intuition with evidence. The official guide is the appropriate reference.

I would compare estimated and observed work, identify where rows expand or filters remove them, and account for realistic data distribution. A plan that works on a tiny development dataset may behave differently on a populated system.

Measurements should also preserve the workload conditions used for comparison.

Include the application

The database is one part of the endpoint. Serialization, repeated calls, network waits, and downstream services can dominate after a query improves.

A useful performance story therefore follows the request through the application as well as the database. Otherwise, a large query improvement can have a surprisingly small effect on the user's wait.

I like optimizations that make the system easier to explain: fewer unnecessary rows, clearer joins, deliberate indexes, and a result contract that matches the interface. Speed is the observable benefit. Understanding why the system did less work is what makes the benefit maintainable.

More from the journal