How to Optimize SQL Query Performance: Why a Query Is Slow and How to Fix It

To optimize a SQL query, find out where the time goes before changing anything: run the execution plan, see which step scans the most rows, then cut that work. Filter early, select only the columns you need, keep indexed columns free of functions, and aggregate before joining large tables.
Key takeaways
- Read the plan first. Every major database can show its execution plan, the step-by-step recipe it follows for your query.
- Most slow queries read far more rows than the answer needs. In our 2-million-row test, a date range instead of a date function cut a query from 351.6 ms to 68.3 ms.
- An index only helps if the query can use it. A lookup took 61.2 ms without an index and 0.007 ms with one.
- A rewrite is finished only when it returns exactly the same rows.
Why does SQL query speed matter for analysts?
Because SQL is where analysts spend their day. In the Stack Overflow Developer Survey 2025, 58.6% of respondents had done extensive work in SQL over the past year, and PostgreSQL was the most used database at 55.6%. Speed also changes how you work: at four seconds a query, you explore; at four minutes, you stop asking follow-up questions.
How do you find out why a query is slow?
Ask the database, not your intuition, and follow the same loop every time.

Figure 1. Change one thing at a time, and never ship a rewrite you have not verified.
EXPLAIN shows the plan
EXPLAIN prints the plan as a tree of steps, each with an estimated cost and row count. PostgreSQL's documentation calls choosing the right plan "absolutely critical for good performance". The cost is in planner units, not milliseconds, so use it to compare two versions of a query, not as a clock.
EXPLAIN ANALYZE shows what really happened.
Adding ANALYZE makes PostgreSQL run the query and report the real row counts and time for each step; adding BUFFERS also shows blocks read from memory or disk. Find the step with the largest actual time, compare estimated with actual rows (a big gap usually means stale statistics), and watch the loops figure. Because the query really runs, wrap any UPDATE or DELETE in BEGIN and ROLLBACK, as the documentation suggests.

Figure 2. A real PostgreSQL plan, annotated. Start at the most indented lines: they run first.
Which terms do you need to know?
- Sequential scan: reading every row of a table.
- Index: a sorted lookup structure that lets the database jump to matching rows.
- Selectivity: the share of rows a filter keeps; 1% is highly selective.
- SARGable: a condition an index can serve, short for Search ARGument-able.
- Cardinality estimate: the planner's guess of how many rows a step returns.
- Covering index: an index holding every column a query needs, so the table is never read.
How do other databases show the plan?
The idea is the same everywhere; the command changes.
Database | Estimated plan (query not run) | Actual plan (query runs) | Also useful |
|---|---|---|---|
PostgreSQL | EXPLAIN | EXPLAIN ANALYZE | Add BUFFERS for block reads |
MySQL 8.0 | EXPLAIN, or EXPLAIN FORMAT=TREE | EXPLAIN ANALYZE (from 8.0.18) | Shows estimated cost beside actual time |
SQL Server | Display Estimated Execution Plan | Include Actual Execution Plan | SET STATISTICS IO for page reads |
BigQuery | Dry run, which estimates bytes processed | Query plan and timeline, after it runs | Stages and steps, with time per stage |
In SQL Server, an estimated plan does not execute the query, so it is safe on production data. If execution plans, joins and indexes are new to you, a hands-on SQL certification course online for beginners that has you write and tune queries on realistic data builds the habit fastest.
What are the most common reasons a query is slow?
A handful of patterns. We measured five common fixes on a synthetic store database (2,000,000 orders, 200,000 customers) in SQLite 3.45.1, taking the median of five runs. Absolute times will differ on your system; the direction holds, because it comes from how indexes and scans work.
Fix | Slow version | Faster version | Before | After |
|---|---|---|---|---|
Range instead of a function on a date | strftime('%Y-%m', order_date) = '2025-03' | order_date >= '2025-03-01' AND order_date < '2025-04-01' | 351.6 ms | 68.3 ms |
Index that matches the expression | LOWER(email) with an index on email | Same query, index on LOWER(email) | 13.9 ms | 0.003 ms |
Index on the lookup column | WHERE customer_id = 4242, no index | Same query, index on customer_id | 61.2 ms | 0.007 ms |
Only the columns you need | SELECT * for a year of orders | SELECT order_id, amount | 1,233.5 ms | 875.7 ms |
Aggregate before joining | Join 2 million orders, then group | Group orders per customer, then join | 2,586.0 ms | 2,205.3 ms |

Figure 3. Measured in SQLite 3.45.1 on synthetic data, median of five runs, 17 November 2026. Index fixes win by orders of magnitude; scan-reducing rewrites win by tens of percent.
The lesson: fixes that let the database use an index win by orders of magnitude, while fixes that still read most of the data win by tens of percent. Chase the index fixes first.
Keep indexed columns bare
An index stores a column's values in sorted order (B-tree is PostgreSQL's default). Wrap the column in a function and an ordinary index can no longer help: in our test the function version's plan read "SCAN orders", the range version "SEARCH orders USING INDEX". The exception, per PostgreSQL's documentation, is an index built on the expression itself, which turned our 13.9 ms email lookup into 0.003 ms.

Figure 4. Keep the indexed column bare, and do the work on the value you compare it with.
Order multicolumn indexes by your filters
PostgreSQL's documentation says a multicolumn index works best with conditions on its leading, leftmost columns. An index on (customer_id, order_date) serves a filter on both, but helps far less with order_date alone. Add payload columns with INCLUDE and the database can answer from the index alone, an index-only scan.
Read less, then join
Google's BigQuery documentation lists "Avoid SELECT *" as a best practice; in our row-store test, selecting two columns instead of six still saved 29%. Aggregating 2 million orders per customer before joining was 15% faster, with identical results.
Keep statistics fresh
The planner picks plans from row estimates stored in PostgreSQL's pg_statistic, which ANALYZE updates. After a large load or delete, run ANALYZE; in MySQL, ANALYZE TABLE; in SQL Server, UPDATE STATISTICS, although it also refreshes them automatically by default.
How does the database choose a join?
From its row estimates, among three strategies described in PostgreSQL's planner documentation. A nested loop looks up each row of one side in the other: fast when one side is small and the other is indexed. A hash join builds an in-memory hash table from one side and probes it with the other: good for large equality joins. A merge join walks two inputs already sorted on the join key. A nested loop over two large tables usually means a missing index or a wrong estimate.

Figure 5. The planner chooses using its row estimates, so wrong estimates lead to the wrong join.
Is a slow query a time problem or a cost problem?
On your own server it mostly costs time. On a warehouse billed by data scanned, such as BigQuery on demand, it costs money too. Fewer columns mean fewer bytes billed. Google's documentation notes that LIMIT on a non-clustered table does not reduce cost, while filtering on a partition column lets BigQuery prune whole partitions. A dry run estimates the bytes before you pay, and a maximum-bytes-billed setting caps any single query.

Figure 6. The same query can be cheap and slow, or fast and expensive, depending on where it runs.
How do you check that a fix worked?
Re-run EXPLAIN ANALYZE on both versions, at least twice each, since the first run may read from disk. Then check the answer: compare row counts and totals, and run EXCEPT in both directions (EXCEPT ALL if duplicates matter, since plain EXCEPT removes them).
SELECT COUNT(*) FROM (
SELECT order_id, amount FROM orders WHERE strftime('%Y-%m', order_date) = '2025-03'
EXCEPT
SELECT order_id, amount FROM orders WHERE order_date >= '2025-03-01' AND order_date < '2025-04-01'
) AS only_in_old;In our test both directions returned 0 rows: the faster version returned exactly the same 55,438 orders.

Figure 7. Eight checks that prevent most slow or expensive queries.
What mistakes make queries slow without anyone noticing?
- Testing on a tiny table. Plans change with volume, so test on realistic data.
- Indexing every slow query. Microsoft's index design guide warns that too many index columns hurt disk space and update performance.
- Hiding a bad join with DISTINCT. The database still builds every duplicate first. Fix the join instead.
- Tuning the wrong query. Start with the queries behind daily dashboards and scheduled jobs.
How does query optimization come up in interviews?
As a reasoning test. Expect three questions: how you would find out why a query is slow (read the plan, find the costliest step, change one thing, re-measure); when an index is not used (functions on the column, low selectivity, stale statistics); and how you would prove a rewrite is correct (counts, totals, EXCEPT both ways).
Frequently asked questions
How to enhance SQL query performance?
Read the execution plan to find the slowest step, then reduce the work there. In practice that means filtering early on indexed columns, keeping those columns free of functions, selecting only the columns you need, and aggregating large tables before joining. Measure before and after, and confirm the results match.
How to optimize a query using an execution plan?
Run EXPLAIN, or EXPLAIN ANALYZE to see real timings. Find the step with the largest actual time and check whether it reads far more rows than it returns. A big gap between estimated and actual rows usually means stale statistics; a full scan on a selective filter usually means a missing or unusable index.
What are the techniques of optimization?
The ones that matter most are index-friendly conditions, the right multicolumn index order, early filtering, selecting only needed columns, aggregating before joining and keeping statistics fresh. On cloud warehouses, partitioning and clustering tables by the columns you filter on also cut the data each query scans
What is a SARGable query?
A SARGable query uses conditions an index can serve. "order_date >= '2025-03-01'" is SARGable; "YEAR(order_date) = 2025" is not, because the function hides the stored values from an ordinary index. The fix is to leave the column bare and move the calculation to the value you compare it with.
Is SQL a good skill to have in 2026?
Yes. In the Stack Overflow Developer Survey 2025, 58.6% of respondents reported extensive work in SQL over the past year, more than reported Python. Most companies keep their data in a SQL database or warehouse, so people who can query it well, and fast, work faster and depend less on others.
How do I improve my SQL skills?
Practise on real, messy data and read the plan of every query that takes more than a few seconds. Rewrite slow queries two or three ways and compare their plans and timings. Learn joins, window functions and CTEs well, and ask someone experienced to review your queries, because reviews catch habits a working query hides.
Conclusion
A slow query is a question the database can answer for you: run the plan, find the step doing the most work, and remove the work the answer does not need. Index fixes win by orders of magnitude, leaner scans by tens of percent, and every rewrite needs verifying.

Figure 8. Six habits that fix most slow analyst queries.
Start with the slowest query you run every day: read its plan, apply one fix, verify the result, and measure the difference.
Thanks for Reading