A slow SQL query is one of the easiest ways to ruin a fast application.
You can have a clean architecture, a great cache, and a powerful server - and still watch a page hang because one query scans a million rows without an index.
Over the years, I have optimized hundreds of SQL queries across many production systems.
Most of the wins come from the same small set of techniques, applied again and again.
Some of them are obvious.
Some of them go against advice you have probably heard.
To make them easy to remember, I have grouped 20 proven techniques into 6 themes you can reach for whenever a query gets slow.
In this post, we will explore:
Write index-friendly (sargable) queries
Use indexes wisely
Avoid functions on columns in WHERE
Avoid leading wildcards in LIKE
Match data types exactly
Fetch only the data you need
Stop using SELECT *
Filter early
Paginate with Keyset instead of OFFSET
Query only what changed
Simplify joins and subqueries
Reduce JOIN complexity
Choose the right JOIN…