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

A One-Stop solution to all your career needs by 10 min read 72x views
How to Optimize SQL Query Performance: Why a Query Is Slow and How to Fix It

Share Post

To optimize a SQL query, discover out anywhere the period goes before changing anything: run the implementation plan, see which stage scans the most rows, afterward cut that work. Filter early, choose lone the columns you need, keep indexed columns liberated of functions, and total before joining ample tables.

Key takeaways

  • Read the scheme first. Every important repository can display its implementation plan, the step-by-step formula it follows for your query.
  • Most dilatory queries peruse far additional rows than the answer needs. In our 2-million-row test, a date range alternatively of a date function cut a query from 351.6 ms to 68.3 ms.
  • An indicator lone helps if the query can use it. A lookup took 61.2 ms without an indicator and 0.007 ms alongside one.
  • A rewrite is completed lone whenever it returns exactly the identical rows.

Why does SQL query speed matter for analysts?

Because SQL is anywhere analysts expend their day. In the Stack Overflow Developer Survey 2025, 58.6% of respondents had done extended activity in SQL complete the former year, and PostgreSQL was the most used repository at 55.6%. Speed additionally changes how you work: at four seconds a query, you explore; at four minutes, you halt asking follow-up questions.

How do you discover out why a query is slow?

Ask the database, not your intuition, and prosecute the identical iteration all time.

Flowchart showing eight steps to diagnose and fix a dilatory SQL query, alongside three decision points

Figure 1. Change one item at a time, and never container a rewrite you have not verified.

EXPLAIN shows the plan

EXPLAIN prints the scheme as a tree of steps, all alongside an estimated disbursal and row count. PostgreSQL's records calls choosing the correct scheme "absolutely crucial for fine performance". The disbursal is in planner units, not milliseconds, so use it to difference two versions of a query, not as a clock.

EXPLAIN ANALYZE shows what really happened.

Adding ANALYZE makes PostgreSQL run the query and study the genuine row counts and period for all step; adding BUFFERS additionally shows blocks peruse from recollection or disk. Find the stage alongside the largest genuine time, difference estimated alongside genuine rows (a big gap normally method old statistics), and observe the loops figure. Because the query really runs, cover any UPDATE or DELETE in BEGIN and ROLLBACK, as the records suggests.

PostgreSQL EXPLAIN ANALYZE output alongside six callouts explaining cost, estimated and genuine rows, loops, buffers, indicator circumstance and implementation time

Figure 2. A genuine PostgreSQL plan, annotated. Start at the most indented lines: they run first.

Which conditions do you need to know?

  • Sequential scan: study all row of a table.
  • Index: a sorted lookup construction that lets the repository jump to matching rows.
  • Selectivity: the portion of rows a display keeps; 1% is extremely selective.
  • SARGable: a circumstance an indicator can serve, abbreviated for Search ARGument-able.
  • Cardinality estimate: the planner's conjecture of how many rows a stage returns.
  • Covering index: an indicator holding all pillar a query needs, so the array is never read.

How do another databases display the plan?

The idea is the identical everywhere; the command changes.

Database

Estimated scheme (query not run)

Actual scheme (query runs)

Also useful

PostgreSQL

EXPLAIN

EXPLAIN ANALYZE

Add BUFFERS for obstacle reads

MySQL 8.0

EXPLAIN, or EXPLAIN FORMAT=TREE

EXPLAIN ANALYZE (from 8.0.18)

Shows estimated disbursal beside genuine time

SQL Server

Display Estimated Execution Plan

Include Actual Execution Plan

SET STATISTICS IO for leaf reads

BigQuery

Dry run, which estimates bytes processed

Query scheme and timeline, following it runs

Stages and steps, alongside period per stage

In SQL Server, an estimated scheme does not execute the query, so it is harmless on manufacturing data. If implementation plans, joins and indexes are new to you, a hands-on SQL certification way online for beginners that has you compose and tune queries on realistic data builds the habit fastest.

What are the most average reasons a query is slow?

A fistful of patterns. We measured five average fixes on a synthetic shop repository (2,000,000 orders, 200,000 customers) in SQLite 3.45.1, taking the median of five runs. Absolute times volition differ on your system; the direction holds, since it comes from how indexes and scans work.

Fix

Slow version

Faster version

Before

After

Range alternatively 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) alongside an indicator on email

Same query, indicator on LOWER(email)

13.9 ms

0.003 ms

Index on the lookup column

WHERE customer_id = 4242, no index

Same query, indicator on customer_id

61.2 ms

0.007 ms

Only the columns you need

SELECT * for a twelvemonth of orders

SELECT order_id, amount

1,233.5 ms

875.7 ms

Aggregate before joining

Join 2 myriad orders, afterward group

Group orders per customer, afterward join

2,586.0 ms

2,205.3 ms

Bar diagram comparing query times before and following five SQL fixes, alongside index-related fixes showing the largest gains

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 repository use an indicator win by orders of magnitude, during fixes that motionless peruse most of the data win by tens of percent. Chase the indicator fixes first.

Keep indexed columns bare

An indicator stores a column's values in sorted command (B-tree is PostgreSQL's default). Wrap the pillar in a function and an average indicator can no longer help: in our test the function version's scheme peruse "SCAN orders", the range type "SEARCH orders USING INDEX". The exception, per PostgreSQL's documentation, is an indicator built on the expression itself, which turned our 13.9 ms email lookup into 0.003 ms.

Comparison of SQL conditions that can and cannot use an index

Figure 4. Keep the indexed pillar bare, and do the activity on the value you difference it with.

Order multicolumn indexes by your filters

PostgreSQL's records says a multicolumn indicator plant finest alongside conditions on its leading, leftmost columns. An indicator on (customer_id, order_date) serves a display on both, but helps far small alongside order_date alone. Add payload columns alongside INCLUDE and the repository can answer from the indicator alone, an index-only scan.

Read less, afterward join

Google's BigQuery records lists "Avoid SELECT *" as a finest practice; in our row-store test, selecting two columns alternatively of six motionless saved 29%. Aggregating 2 myriad orders per client before joining was 15% faster, alongside identical results.

Keep data fresh

The planner picks plans from row estimates stored in PostgreSQL's pg_statistic, which ANALYZE updates. After a ample burden or delete, run ANALYZE; in MySQL, ANALYZE TABLE; in SQL Server, UPDATE STATISTICS, although it additionally refreshes them automatically by default.

How does the repository choose a join?

From its row estimates, among three strategies described in PostgreSQL's planner documentation. A nested iteration looks up all row of one flank in the other: accelerated whenever one flank is small and the another is indexed. A hash associate builds an in-memory hash array from one flank and probes it alongside the other: fine for ample equality joins. A merge associate walks two inputs already sorted on the associate key. A nested iteration complete two ample tables normally method a missing indicator or a incorrect estimate.

Decision diagram choosing between nested loop, merge and hash joins

Figure 5. The planner chooses using its row estimates, so incorrect estimates guide to the incorrect join.

Is a dilatory query a period issue or a disbursal problem?

On your own server it mostly expenses time. On a storage billed by data scanned, specified as BigQuery on demand, it expenses prosperity too. Fewer columns average small bytes billed. Google's records notes that LIMIT on a non-clustered array does not decrease cost, during filtering on a partition pillar lets BigQuery prune entire partitions. A dry run estimates the bytes before you pay, and a maximum-bytes-billed environment caps any sole query.

Infographic comparing how SQL optimizations preserve period on self-hosted databases and prosperity on bytes-billed warehouses

Figure 6. The identical query can be cheap and slow, or accelerated and expensive, depending on anywhere it runs.

How do you inspect that a fix worked?

Re-run EXPLAIN ANALYZE on the two versions, at smallest twice each, since the archetypal run may peruse from disk. Then inspect the answer: difference row counts and totals, and run EXCEPT in the two 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 the two directions returned 0 rows: the faster type returned exactly the identical 55,438 orders.

Checklist of eight steps to obtain before operating a dense SQL query

Figure 7. Eight checks that forestall most dilatory or costly queries.

What mistakes create queries dilatory without anyone noticing?

  1. Testing on a small table. Plans alter alongside volume, so test on realistic data.
  2. Indexing all dilatory query. Microsoft's indicator scheme guide warns that too many indicator columns hurt disk area and update performance.
  3. Hiding a bad associate alongside DISTINCT. The repository motionless builds all copy first. Fix the associate instead.
  4. Tuning the incorrect query. Start alongside the queries rearward regular dashboards and scheduled jobs.

How does query optimization arrive up in interviews?

As a reasoning test. Expect three questions: how you would discover out why a query is dilatory (read the plan, discover the costliest step, alter one thing, re-measure); whenever an indicator is not used (functions on the column, low selectivity, old statistics); and how you would demonstrate a rewrite is accurate (counts, totals, EXCEPT the two ways).

Frequently asked questions

How to enhance SQL query performance?

Read the implementation scheme to discover the slowest step, afterward decrease the activity there. In custom that method filtering first on indexed columns, keeping those columns liberated of functions, selecting lone the columns you need, and aggregating ample tables before joining. Measure before and after, and verify the results match.

How to optimize a query using an implementation plan?

Run EXPLAIN, or EXPLAIN ANALYZE to see genuine timings. Find the stage alongside the largest genuine period and inspect whether it says far additional rows than it returns. A big gap between estimated and genuine rows normally method old statistics; a complete scan on a selective display normally method a missing or unusable index.

What are the techniques of optimization?

The ones that matter most are index-friendly conditions, the correct multicolumn indicator order, first filtering, selecting lone needed columns, aggregating before joining and keeping data fresh. On haze warehouses, partitioning and clustering tables by the columns you display on additionally cut the data all query scans

What is a SARGable query?

A SARGable query uses conditions an indicator can serve. "order_date >= '2025-03-01'" is SARGable; "YEAR(order_date) = 2025" is not, since the function hides the stored values from an average index. The fix is to depart the pillar naked and move the calculation to the value you difference it with.

Is SQL a fine accomplishment to have in 2026?

Yes. In the Stack Overflow Developer Survey 2025, 58.6% of respondents reported extended activity in SQL complete the former year, additional than reported Python. Most companies keep their data in a SQL repository or warehouse, so group who can query it well, and fast, activity faster and depend small on others.

How do I enhance my SQL skills?

Practise on real, messy data and peruse the scheme of all query that takes additional than a few seconds. Rewrite dilatory queries two or three ways and difference their plans and timings. Learn joins, opening functions and CTEs well, and ask person informed to assessment your queries, since reviews capture habits a operating query hides.

Conclusion

A dilatory query is a inquiry the repository can answer for you: run the plan, discover the stage doing the most work, and eliminate the activity the answer does not need. Index fixes win by orders of magnitude, leaner scans by tens of percent, and all rewrite needs verifying.

6afc47caab7af.webp

Figure 8. Six habits that fix most dilatory expert queries.

Start alongside the slowest query you run all day: peruse its plan, use one fix, verify the result, and measure the difference.
Thanks for Reading

Other Article A One-Stop solution to all your career needs
↑
Close Right Ads
Close Left Ads