Our SQL queries are slow

Short answerStart with EXPLAIN ANALYZE on the slow query: it shows which step of the plan takes the time. Most fixes are free and quick. Add an index on the columns in WHERE and JOIN, select only the columns you need and refresh the table statistics. Then log or track slow queries so you fix the ones that cost the most.

01

Run EXPLAIN ANALYZE and read the plan

Put EXPLAIN ANALYZE in front of the slow query (MySQL and PostgreSQL). In SQL Server Management Studio, turn on Include Actual Execution Plan and run it. Look for the step with the most time and for big gaps between estimated and actual rows.

Good if you don't know yet where the time goes

Skip if the query is an UPDATE or DELETE you can't wrap in BEGIN and ROLLBACK

Using EXPLAIN · EXPLAIN · MySQL · Microsoft Learn

Do it yourself
CostFree
EffortLow
HelpsToday
02

Add an index on the WHERE and JOIN columns

Take the columns the slow query filters and joins on and index them, for example CREATE INDEX ON orders (customer_id). Run the plan again to check the index is used. In most cases one column per index is enough. Every index slows down writes a little, so drop the ones no query uses.

Good if the plan shows a full scan of a big table

Skip if the table is small or gets far more writes than reads

Indexes, Introduction · Multicolumn Indexes · Microsoft Learn

Do it yourself
CostFree
EffortLow
HelpsToday
03

Select only the columns you need

Replace SELECT * with the columns the code actually uses. If every column the query needs sits in one index, the database can answer from the index alone (an index-only scan) without touching the table.

Good if the query feeds a list or report with a few fields

PostgreSQL

Do it yourself
CostFree
EffortLow
HelpsToday
04

Rewrite correlated subqueries as JOINs

A subquery that runs once for every row of the outer query can often be written as a JOIN. Many databases plan both forms the same way, so measure before and after. The JOIN tends to win where the subquery checks whether a matching row exists.

Good if the plan runs the same subquery again for every row

Skip if the plan already treats both forms the same

Microsoft Learn

Do it yourself
CostFree
EffortMedium
HelpsThis week
05

Refresh the table statistics

The planner picks its plan from statistics about your data, and these go out of date as rows change. Run ANALYZE on the table in PostgreSQL, or UPDATE STATISTICS in SQL Server, after big imports or deletes. Check that autovacuum or AUTO_UPDATE_STATISTICS is switched on so this keeps happening.

Good if the query got slower over time with no code change

PostgreSQL · Microsoft Learn

Do it yourself
CostFree
EffortLow
HelpsToday
06

Log every query that runs too long

In PostgreSQL, set log_min_duration_statement, for example to 250ms, and every slower statement lands in the log. In MySQL, turn on slow_query_log and summarise the file with mysqldumpslow. The free pgBadger turns a PostgreSQL log into a readable report.

Good if users say it's slow but nobody knows which query

PostgreSQL · MySQL · pgBadger

Tool
CostFree
EffortLow
HelpsThis week
07

Use your database's query performance insights

PostgreSQL's pg_stat_statements tracks run time for every statement. Load it in shared_preload_libraries, restart, then sort by total_exec_time to find the queries that cost the most. SQL Server and Azure SQL have Query Store, which keeps old plans so you can see when a plan change made a query slower and force the old plan back.

Good if you want the top offenders across the whole server

Skip if you can't restart the server this week (PostgreSQL)

PostgreSQL · Microsoft Learn

Tool
CostFree
EffortMedium
HelpsThis week
08

Turn on automatic tuning in Azure SQL

Azure SQL Database can create missing indexes and drop unused ones for you. It checks afterwards whether queries got faster and undoes the change if they didn't. Switch the options on for your database in the Azure portal.

Good if your database already runs on Azure SQL Database

Skip if you run your own database server

Microsoft Learn

Tool
Cost€
EffortLow
HelpsThis week
09

Bring in a DBA or database consultant

If slow queries keep coming back or the fix means reworking the schema, get a database expert to review it. The PostgreSQL project lists companies that offer commercial support, sorted by region. Send them your slowest queries with their EXPLAIN ANALYZE output so they start on the real problem.

Good if you've tried the fixes above and it's still slow

PostgreSQL

Expert
Cost€€€
EffortMedium
HelpsThis month

When it's bigger than a quick fix

Bring in a DBA, a database consultant or your vendor's support when one query keeps slowing the whole application, indexes and fresh statistics did not help, or the fix means changing the schema of a busy production table.

EXPLAIN ANALYZE really runs the statement. On an INSERT, UPDATE or DELETE it changes your data, so wrap it in BEGIN and ROLLBACK, and never test it on production data without that.

Professional Services · EXPLAIN

Questions people ask

Why does my SQL query slow down over time?

Often because the table statistics are out of date: the data changed, and the planner still picks its plan from the old numbers. Run ANALYZE or UPDATE STATISTICS and check that automatic updates are on.

Is EXPLAIN ANALYZE safe to run?

It actually executes the query. For a SELECT that's fine. For INSERT, UPDATE or DELETE, wrap it in BEGIN and ROLLBACK so your data stays unchanged.

Does adding an index always make a query faster?

No. An index helps queries that filter or join on that column, but it slows down every insert and update a little. Check the plan before and after, and drop indexes nothing uses.

Are JOINs faster than subqueries?

Usually there is no difference, because the database plans both the same way. A JOIN can be faster where the subquery checks whether a matching row exists.

How do I find the slowest queries on my database?

Use pg_stat_statements in PostgreSQL, the slow query log in MySQL or Query Store in SQL Server. Sort by total time, not by single runs.

Sources

  1. PostgreSQL: Using EXPLAIN
  2. PostgreSQL: EXPLAIN
  3. MySQL: EXPLAIN Statement
  4. Microsoft Learn: Display an actual execution plan
  5. PostgreSQL: Indexes, Introduction
  6. PostgreSQL: Multicolumn Indexes
  7. Microsoft Learn: Tune nonclustered indexes with missing index suggestions
  8. PostgreSQL: Index-Only Scans and Covering Indexes
  9. Microsoft Learn: Subqueries (SQL Server)
  10. PostgreSQL: ANALYZE
  11. Microsoft Learn: Statistics
  12. PostgreSQL: Error Reporting and Logging
  13. MySQL: The Slow Query Log
  14. pgBadger: PostgreSQL log analyzer
  15. PostgreSQL: pg_stat_statements
  16. Microsoft Learn: Monitor performance by using the Query Store
  17. Microsoft Learn: Automatic tuning overview (Azure SQL)
  18. PostgreSQL: Professional Services