--- title: "10 Ways to Speed Up Slow SQL Queries" author: "Shobit Singh" published: "2026-11-23T10:03:57.615Z" updated: "2026-11-23T10:03:57.615Z" url: "https://zyvop.com/10-ways-to-speed-up-slow-sql-queries-rmpem" canonical: "https://zyvop.com/10-ways-to-speed-up-slow-sql-queries-rmpem" tags: ["indexing","postgresql","SQL","query-optimization","database performance"] --- # 10 Ways to Speed Up Slow SQL Queries Ten practical fixes for slow SQL queries, from replacing SELECT * to writing sargable predicates, with diagrams that show why each one works. ![Cover image]() _From_ `SELECT *` _to sargable predicates: practical fixes, with diagrams that show why they work._ * * * Most slow queries share a handful of causes: reading more data than needed, defeating an index, or making the database do work again and again. The ten fixes below cover the most common ones, roughly in the order you'd apply them. The golden rule is to **measure, change one thing, and measure again**. ```mermaid flowchart LR A["Find the slow query"] --> B["Read its execution plan"] B --> C["Fix the biggest cost"] C --> D["Re-measure"] D -->|"still slow"| B D -->|"fast enough"| E["Stop"] ``` The examples use two tables, `orders` (`order_id`, `customer_id`, `order_date`, `amount`, `status`) and `customers` (`customer_id`, `first_name`, `last_name`, `email`), with PostgreSQL syntax. A dialect table near the end covers MySQL and SQL Server. * * * ## 1\. Read the Execution Plan First Guessing is the slowest way to tune. Ask the database how it runs the query: ```sql EXPLAIN (ANALYZE, BUFFERS) SELECT order_id, amount FROM orders WHERE customer_id = 42 AND order_date >= '2026-01-01'; ``` `EXPLAIN ANALYZE` actually **executes** the query. For `INSERT`, `UPDATE`, or `DELETE`, wrap it in `BEGIN` ... `ROLLBACK`. (From PostgreSQL 18, `ANALYZE` includes buffer statistics automatically.) | What the plan shows | What it usually means | | --- | --- | | Sequential scan on a big table with a selective filter | Missing index, or a predicate that can't use one | | Estimated rows far from actual rows | Stale statistics (tip 10) | | Large "Rows Removed by Filter" | The filter runs after reading rows instead of using an index | | Sort that spills to disk | Too many rows sorted; an index could provide the order | | Nested loop with a huge loop count | Missing join index, or an N+1 shape (tip 9) | * * * ## 2\. Stop Using `SELECT *` Fetching every column costs more than it looks: more data read from disk, more sent over the network, and more memory used. It also blocks a powerful optimization, the **covering index**. ```sql -- Slow: reads every column, including wide text and JSON SELECT * FROM orders WHERE customer_id = 42; -- Better: only what the page actually shows SELECT order_id, order_date, amount FROM orders WHERE customer_id = 42; ``` ```mermaid flowchart LR A["SELECT *"] --> B["Needs every column"] B --> C["Index lookup, then fetch each
full row from the table"] D["SELECT amount"] --> E["Needs one column"] E --> F["Answered from the index alone
covering index"] ``` Naming columns also protects your code when someone adds a column to the table later. * * * ## 3\. Write Sargable Predicates **Sargable** means "Search ARGument ABLE": the database can use an index to jump straight to matching rows. The rule is simple: **keep the indexed column bare** on one side of the comparison. Wrap it in a function or math and the engine must compute the expression for every row. ```mermaid flowchart TD A["WHERE EXTRACT(YEAR FROM order_date) = 2026"] --> B["Engine computes the function
for every row"] B --> C["Index on order_date can't be searched:
full scan"] D["WHERE order_date in a range
2026-01-01 up to 2027-01-01"] --> E["Column stays bare"] E --> F["Index seek to the range:
reads only matching rows"] ``` | Slow (non-sargable) | Fast (sargable) | | --- | --- | | `WHERE EXTRACT(YEAR FROM order_date) = 2026` | `WHERE order_date >= '2026-01-01' AND order_date < '2027-01-01'` | | `WHERE order_date::date = '2026-03-01'` | `WHERE order_date >= '2026-03-01' AND order_date < '2026-03-02'` | | `WHERE amount * 1.18 > 100` | `WHERE amount > 100 / 1.18` | | `WHERE last_name LIKE '%son'` (leading wildcard) | `WHERE last_name LIKE 'Son%'`, or a trigram or full-text index | | `WHERE LOWER(email) = 'a@b.com'` | Same query plus an expression index (below) | Use half-open ranges (`>=` start and `<` next start) for dates; they stay correct for timestamps and avoid end-of-day bugs. When you genuinely need a function in the filter, index the function's result: ```sql CREATE INDEX idx_customers_email_lower ON customers (LOWER(email)); ``` Other sargability traps: - **Prefix** `LIKE` **in PostgreSQL:** a plain B-tree index supports `LIKE 'abc%'` only with the `C` collation, or when built with `text_pattern_ops`. For `LIKE '%abc%'`, use a trigram index (`CREATE EXTENSION pg_trgm;` then `CREATE INDEX ... USING gin (col gin_trgm_ops)`). - **Mismatched types:** comparing a text column to a number, or a `VARCHAR` column to an `NVARCHAR` parameter in SQL Server, can make the engine convert the column instead of the value. Match types exactly. - `OR` **across different columns:** some engines can't use one index for it. If the plan shows a scan, try `UNION ALL` of two indexed queries. PostgreSQL 18 handles more `OR` conditions with an index, but check the plan. * * * ## 4\. Index the Columns You Filter, Join, and Sort On An index lets the database find rows without reading the whole table, like a book's index versus reading every page. ```mermaid flowchart LR subgraph N["No index on customer_id"] N1["Read every row"] --> N2["Keep the matches"] end subgraph Y["Index on customer_id"] Y1["Jump to customer_id = 42"] --> Y2["Read only those rows"] end ``` ```sql CREATE INDEX idx_orders_customer ON orders (customer_id); ``` - **Index foreign keys yourself.** PostgreSQL indexes primary keys and unique constraints automatically, but not the referencing side of a foreign key, so joins and cascading deletes can end up scanning. - **Index selective columns.** A column with only a few distinct values (like a boolean) rarely helps on its own. A **partial index** covers just the rows you query: ```sql CREATE INDEX idx_orders_pending ON orders (order_date) WHERE status = 'pending'; ``` - **Indexes aren't free.** Each one slows `INSERT`, `UPDATE`, and `DELETE` and uses disk space. In PostgreSQL, `pg_stat_user_indexes.idx_scan = 0` can reveal unused ones (but keep indexes that enforce unique constraints). - **On live systems**, use `CREATE INDEX CONCURRENTLY` in PostgreSQL to avoid blocking writes. * * * ## 5\. Get Composite Index Column Order Right In a multi-column index, order matters. A good default: **equality columns first, then the range column, then the sort column.** ```sql SELECT order_id, amount FROM orders WHERE customer_id = 42 AND status = 'completed' ORDER BY order_date DESC; CREATE INDEX idx_orders_cust_status_date ON orders (customer_id, status, order_date); ``` The index narrows to one customer and status, and the rows are already stored in `order_date` order, so **no separate sort is needed**: ```mermaid flowchart LR subgraph A["Index on customer_id only"] A1["Seek customer_id = 42"] --> A2["Sort rows by order_date"] --> A3["Return"] end subgraph B["Index on customer_id, order_date"] B1["Seek customer_id = 42"] --> B2["Rows already in
order_date order"] --> B3["Return"] end ``` Two more rules of thumb: - **Leftmost prefix:** an index on `(a, b)` reliably serves filters on `a`, or on `a` and `b`, but not on `b` alone. Some engines can "skip scan" in limited cases (PostgreSQL 18, Oracle, MySQL 8), mainly when `a` has few distinct values, so don't depend on it. - **Covering indexes:** add the selected columns so the query never touches the table (`INCLUDE` in PostgreSQL 11+ and SQL Server): ```sql CREATE INDEX idx_orders_cust_covering ON orders (customer_id) INCLUDE (amount); ``` In PostgreSQL, index-only scans also depend on `VACUUM` keeping the visibility map current. * * * ## 6\. Do Less Work: Filter Early, Limit Rows, Skip Needless Steps Every row a query touches costs time, so shrink the data as early as you can. | Habit | Why it costs | Fix | | --- | --- | --- | | Row filters in `HAVING` | Optimizers often push them down, but not always | Use `WHERE` for rows; `HAVING` only for aggregates | | `UNION` when duplicates don't matter | Forces a sort or hash to remove duplicates | Use `UNION ALL` | | `DISTINCT` to hide duplicate rows | Often masks a join that fans out | Fix the join or filter | | `ORDER BY` inside subqueries or CTEs | Sorting work that's usually discarded | Remove it, and sort once at the end | | No `LIMIT` on exploratory queries | Returns far more rows than anyone reads | Add `LIMIT` | ```sql -- Row condition belongs in WHERE SELECT customer_id, SUM(amount) AS total FROM orders WHERE status = 'completed' -- filters rows before grouping GROUP BY customer_id HAVING SUM(amount) > 1000; -- filters groups after aggregating ``` * * * ## 7\. Replace `OFFSET` Pagination with Keyset Pagination `OFFSET 250000` doesn't skip rows; the database reads and discards them. Deep pages get slower and slower. **Keyset pagination** remembers where the last page ended and seeks straight there. ```mermaid flowchart LR subgraph O["OFFSET 250000 LIMIT 20"] O1["Read 250,000 rows"] --> O2["Discard them"] --> O3["Return the next 20"] end subgraph K["Keyset: after the last seen id"] K1["Seek straight to the last seen id"] --> K2["Return the next 20"] end ``` ```sql -- Slow on deep pages SELECT order_id, order_date, amount FROM orders ORDER BY order_id LIMIT 20 OFFSET 250000; -- Fast: pass in the last order_id from the previous page SELECT order_id, order_date, amount FROM orders WHERE order_id > :last_seen_id ORDER BY order_id LIMIT 20; ``` When sorting by a non-unique column, add a unique tie-breaker and compare both together: ```sql WHERE (order_date, order_id) < (:last_date, :last_id) ORDER BY order_date DESC, order_id DESC LIMIT 20; ``` The trade-off: you can't jump to "page 500" directly, which suits infinite scroll and "next" buttons. Row-value comparison works in PostgreSQL and MySQL; SQL Server needs it written out with `OR`. * * * ## 8\. Use `EXISTS` for Existence Checks If you only need to know whether any row exists, don't count them all. ```sql -- Slow: counts every matching row just to compare with zero SELECT COUNT(*) FROM orders WHERE customer_id = 42; -- Fast: stops at the first match SELECT EXISTS (SELECT 1 FROM orders WHERE customer_id = 42); ``` ```mermaid flowchart LR A["COUNT(*) > 0"] --> B["Finds and counts
every matching row"] C["EXISTS"] --> D["Stops at the first
matching row"] ``` For "customers with no orders," prefer `NOT EXISTS` over `NOT IN`: ```sql SELECT c.customer_id FROM customers c WHERE NOT EXISTS ( SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id ); ``` Modern optimizers usually treat `IN` and `EXISTS` the same, but `NOT IN` is different: because of `NULL` semantics it often can't become an efficient anti-join, and a single `NULL` in the subquery makes it return nothing. `NOT EXISTS` avoids both problems. * * * ## 9\. Kill N+1 Queries and Row-by-Row Loops The N+1 pattern runs one query to fetch a list, then one more query for each item in it. Each round trip adds latency, and a hundred "fast" queries add up. ```mermaid flowchart LR subgraph B["N+1: 101 round trips"] B1["1 query:
get 100 customers"] --> B2["100 more queries:
one per customer's orders"] end subgraph G["Fixed: 1 round trip"] G1["One JOIN or IN query
returns all the orders"] end ``` ```sql -- N+1: this runs once per customer, from a loop in application code SELECT order_id, amount FROM orders WHERE customer_id = ?; -- One query for the whole list SELECT customer_id, order_id, amount FROM orders WHERE customer_id IN (1, 2, 3, /* ... */ 100); -- Batch writes instead of one INSERT per row INSERT INTO orders (customer_id, amount) VALUES (1, 10.00), (2, 25.50), (3, 8.75); ``` ORMs create N+1 problems easily, so look for "eager loading" or "join fetch" options. For large imports, use the database's bulk loader (`COPY` in PostgreSQL). * * * ## 10\. Keep Statistics Fresh and Tables Healthy The planner chooses plans using **statistics** about your data, such as how many rows match a filter. When they're stale, it can pick a plan that's wildly wrong, like a nested loop over millions of rows. ```mermaid flowchart TD A["EXPLAIN ANALYZE shows estimated rows
far from actual rows"] --> B["Run ANALYZE on the table"] B --> C{"Estimates now close?"} C -- Yes --> D["Plan usually improves"] C -- No --> E["Check correlated columns,
skewed data, or rewrite the query"] ``` ```sql ANALYZE orders; ``` - Run `ANALYZE` after bulk loads or large deletes. PostgreSQL's autovacuum analyzes tables automatically, but it can lag behind big changes. - Heavy `UPDATE` and `DELETE` activity leaves dead rows behind. `VACUUM` (usually automatic) reclaims them and keeps index-only scans effective. - For columns whose values are related (such as city and postal code), PostgreSQL's extended statistics (`CREATE STATISTICS`) help the planner estimate combined filters. - Since PostgreSQL 18, `pg_upgrade` keeps planner statistics, so plans don't degrade while the first `ANALYZE` runs after an upgrade. * * * ## Where to Start When a query is slow, this flowchart points to the right tip: ```mermaid flowchart TD S["Slow query"] --> P["Run EXPLAIN ANALYZE"] P --> Q1{"Big sequential scan with
a selective filter?"} Q1 -- Yes --> F1["Add an index or make the predicate
sargable: tips 3, 4, 5"] Q1 -- No --> Q2{"Estimated rows far
from actual rows?"} Q2 -- Yes --> F2["Refresh statistics: tip 10"] Q2 -- No --> Q3{"Big sort or deep OFFSET?"} Q3 -- Yes --> F3["Index for the sort, or use keyset
pagination: tips 5, 7"] Q3 -- No --> Q4{"Same query repeated
many times?"} Q4 -- Yes --> F4["Batch or join: tip 9"] Q4 -- No --> F5["Fetch fewer columns and rows:
tips 2, 6, 8"] ``` ## Dialect Differences | Task | PostgreSQL | MySQL | SQL Server | | --- | --- | --- | --- | | See the actual plan | `EXPLAIN (ANALYZE)` | `EXPLAIN ANALYZE` (8.0.18+) | Actual Execution Plan, or `SET STATISTICS IO, TIME ON` | | Refresh statistics | `ANALYZE` | `ANALYZE TABLE` | `UPDATE STATISTICS` | | Covering index | `INCLUDE` | Add the columns to the index | `INCLUDE` | | Index on an expression | Expression index | Functional index (8.0.13+) | Computed column, then index it | | Limit rows | `LIMIT` | `LIMIT` | `TOP` or `OFFSET ... FETCH` | * * * ## Final Thoughts Almost every slow query comes back to one of three questions: Is the database reading more rows than necessary? Is it reading more columns than necessary? Or is it repeating work it could do once? The plan tells you which, and the ten fixes above map to the answers. Resist the urge to add indexes blindly. Each one has a cost, and a better query often beats a new index. If a query is still too slow after these fixes, the next options are table partitioning, materialized views, caching, or read replicas.