# 10 Ways to Speed Up Slow SQL Queries

_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 Diagram](https://mermaid.ink/img/pako:eNpVj8FuwjAMhl_F8zk9TNqph0kUhpi0Xai2C-GQtm4bLY27xB0w4N2nBglpR_v_9Pn3GWtuCHNsHR_q3gSBt632AACLnca19Q1ITxAdH-B7onDSuIcse4Zip3FLpgErEehI9SSWPYzOeI37m6JI5DKJjslT2a6jKFBzlDu2TNgqCbOBTJwC3cPVHF40RrHOpR4aL1D8D1sTBcjz1PVz-rLTWAqPGveocKAwGNtgfkbpaZi_bag1kxNUt82nCdZUjuLMtOxlbQbrTphjZsbRURZPUWhQUDjrv95NXaZ5zV4UaCypY4KPV40KtlyxsIINuR8SWxsFi2CNUxCNj1mkYFtU6Uhpf-cuj0_jEa9XhVW3ZMcBc3w49FYIr3_iDYYX?type=png)

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 or hard-to-estimate data (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, too little work_mem, or 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 Diagram](https://mermaid.ink/img/pako:eNpdkMFqwkAQhl9lOseyoRR6CkVQG6lgezBtL1kPm2RiFjc7YXdjtOK7l0Sqpcf5-eafjzlhwSVhjJXhvqiVC7BaSwsAMM0kpskqmX_AvcQNRNEEZpnEd6LSA-3JHaFg0zVW4uayMhuheSZxaUs6gGHeda2AUJOFikJRA6mifs7dw6TqjAHHPVSOm4GAoHJD166X23nVcGfDr0NydWBL_w2SEVlkEqfW9-SovPXr0UkZtjQa6OpPrG1hupI8hFqFWysKbMg1SpcYnzDU1AzPKqlSnQkoLsmXcnpw9wNTsQ0L1WhzxBgj1baGIn_0gRoBM6Pt7k0V6Tgv2AYBElPaMsHnUqKANeccWMArmT0FXSgBU6eVEeCV9ZEnpysU45FUfw8uj0_tAc9ngfl2zoYdxnjX1zoQnn8AVS6c1g?type=png)

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 Diagram](https://mermaid.ink/img/pako:eNpNkWFr2zAQhv_K7b5sA5klZWxgukKSOrQfysDJ1o0ojLN8tkVlyUhyU6_kvw_bLPSjjrv3eV70isqVjClWxp1UQz7C_lZaAIDVQeLjXZZnkP3a56vN_sPvbJXDNv_-AM6X7P-UFPkjfIOrxdUXiUdIkhtYHyRmttaWQbm26yMHiA1D1VsVtbPXhf90UzkP_Mx-AO9OEo8zcD0FbA4S723JL-DsGw4osu8jFAyByauGy3SO6o2BoMheYm4v3m-utQUCT7bm6Wo0ThbLZLGEvoPoxgpf58H_ItlB4saZvrUQIg0BCvJ8gWTTzvbiGpifxpyx6oSZ7TxTGcBZM0BLUTXa1mPlIPGIAlv2LekS01eMDbfjN5RcUW8iinnyk7ymwnAYdypn45ZabQZMMaGuM5yEIURuBayNtk8PpHbTe-tsFCBxx7Vj-HEvUUDuChedgDs2zxy1IgErr8kICGRDEtjrCsUE2em_o8vyc_eC57PAot444zym-O7U6Mh4_gewmLa0?type=png)

| Slow (non-sargable) | Fast (sargable) |
| --- | --- |
| WHERE EXTRACT(YEAR FROM order_date) = 2026 | WHERE order_date &gt;= '2026-01-01' AND order_date &lt; '2027-01-01' |
| WHERE order_date::date = '2026-03-01' | WHERE order_date &gt;= '2026-03-01' AND order_date &lt; '2026-03-02' |
| WHERE amount * 1.18 &gt; 100 | WHERE amount &gt; 100 / 1.18 |
| WHERE last_name LIKE '%son' (leading wildcard) | LIKE 'Son%' only if "starts with" is what you need. For "ends with" or "contains", use a trigram 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. (The `::date` row assumes `order_date` is a timestamp.)

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`. That operator class serves pattern matching and equality but not ordinary comparisons like `<` and `>`, so you may need a second, default index. For `LIKE '%abc%'`, use a trigram index (`CREATE EXTENSION pg_trgm;` then `CREATE INDEX ... USING gin (col gin_trgm_ops)`).
    
-   **Mismatched types:** MySQL converts every row's value when you compare a string column to a number, and SQL Server can convert the column when you compare a `VARCHAR` column to an `NVARCHAR` parameter. Either way the index may stop working. (PostgreSQL usually raises an error instead.) Match types exactly.
    
-   `OR` **across different columns:** many engines can combine separate indexes (PostgreSQL's bitmap OR, MySQL's index merge), and PostgreSQL 18 handles more `OR` cases with an index. If the plan still shows a scan, try a `UNION` of two indexed queries. Don't use `UNION ALL` here unless the second query excludes rows the first already returned, because a row that matches both conditions would appear twice.
    

* * *

## 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 Diagram](https://mermaid.ink/img/pako:eNqFkE1Lw0AQhv_KOOfNoaWngIIKxfqRQ4tCyRbZJJNkcXcn7G7axtL_LmmpqBfnNsM7PA_vAUuuCFOsDe_KVvkIz0vpAABCXzRedS1kucSMQbuK9sAOyj5EtuTfdSVxcw6Pk01yiUtSFdCW_ACedxI3kCQ3kE1ziU9EHcSWwKpYthS-n8lVf5DrXOLiP9565D32toPIP0NwDbPphbyeXqTYmQFiy4FGs190FGjJW6UrTA8YW7JjJRXVqjcRxfnyprxWhaEwZmp2ca6sNgOmmKiuM5SEIUSyAu6Mdh8vqlyd9jm7KEDiihomeF1IFLDkgiMLeCCzpahLJeDWa2UEBOVCEsjrGsUJstKfo8tk1u3xeBRYNPds2GOKV7tWR8LjF7o8k3Y?type=png)

```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 adds write overhead (on `INSERT`, `DELETE`, and many `UPDATE`s) and uses disk space. In PostgreSQL, `pg_stat_user_indexes.idx_scan = 0` can reveal unused ones once statistics have been collected for long enough (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 column you sort by**, then any range-filter columns. A range condition ends the useful part of the index: columns after it can no longer narrow the seek or return rows in order.

```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 its entries are already sorted by `order_date` within that group, so **no separate sort is needed**:

![Mermaid Diagram](https://mermaid.ink/img/pako:eNqFkFFrwjAQx7_K7Z5Ths6nsgntQCZsL5XtxYqkzdUG01xJ0mknfvdRBcWxsbzd8bv__S4HLFkRxlgZ3pW1dAFes9wCAPiu2DjZ1pAsc5xbRXtgC2XnAzfk1loBW9PnuDrjw0tGyxwXRNsb7Akm4xxXEEVTSMYDwS6A452Hogd2itxayUAX5mGZY0ahc_aSTlb9sEr_sBK3iVe59F-5dJDLBi9pHEnVg7aPhbufXhPP4ZeB301RYEOukVphfMBQUzP8sKJKdiagOHc-pNOyMOQHpmIbZrLRpscYI9m2hiLf-0CNgNRou32T5eJUz9gGAcMhGyZ4n-coIOOCAwt4IfNJQZdSQOK0NAK8tD7y5HSF4rRkob8Gl9Gk3ePxKLDYPLNhhzHe7WodCI_fgNis7g?type=png)

The order of the range and sort columns matters. For `WHERE customer_id = 42 AND amount > 500 ORDER BY order_date`:

```text
INDEX (customer_id, amount, order_date)  -> seeks on the range, then needs an extra sort step
INDEX (customer_id, order_date, amount)  -> no sort step; the range is checked while reading in order
```

If the range filter is very selective, the first layout can still win, because sorting a small result is cheap. Compare the plans.

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 Diagram](https://mermaid.ink/img/pako:eNqFkE1vwjAMhv-K53MqFbZdepi0LzQECAnYLpSD27o0Ik1QYgYM8d-nFGnapknzzfb72o99wtJVjBnWxu3LhrzAeJZbAICwK9aetg1MlzlOB4P58wL6t2mapjAeToYL6Kc5ri7aGNPeMscZUxVVKsq824ccV5AkdzDtL3N80qEkX4E03H41rjub7LyNdbB8kO-j2Va_eEbLHEd8DCwZUC3sO5-hIBCYLejqB9cocs2ZNxDEk143AuL-snQ4o_6_OKiwZd-SrjA7YbwlPrDimnZGUF0qb-Q1FYZD1NTOyoBabY6YYULbreEkHINwq-DBaLuZUDnv8oGzoiDyrh3D6zBHBTNXOHEKXti8s-iSFNx7TUZBIBuSwF7XqLolc_0RWXo32wOezwqL9aMzzmOGV_tGC-P5E2XwnOU?type=png)

```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`. In PostgreSQL, keep every column in the `ORDER BY` in the same direction so the index can be used for the comparison.

* * *

## 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 Diagram](https://mermaid.ink/img/pako:eNpdjl1Lw0AQRf_KOE8qG1TwKUihrRYLfkDTipDtwySZJIub3bA7ba0l_13a4ouP93I59xyw9BVjirX1u7KlIPCy0A4AYJxrnL6v3paX11cwgluNa0iSEUxyjTPjqgjkKij9xkl8KMLNiLcc9tCRlK1xDQS_07g-s6a5xqfPebbM_iiPucZMfB-BBKRlqE2IcuL8I6DCjkNHpsL0gNJyd_StuKaNFVTn5oOCocJyPG5q72RGnbF7TDGhvrecxH0U7hRMrHFfr1RmpzzzThRozLjxDKu5RgULX3jxCp7ZbllMSQrGwZBVEMnFJHIwNarTSWZ-ji539_03DoPCopl66wOmeLFrjTAOv_Vnc40?type=png)

(SQL Server has no `SELECT EXISTS (...)`; use `IF EXISTS (...)` or `SELECT CASE WHEN EXISTS (...) THEN 1 ELSE 0 END`.)

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, PostgreSQL can't turn `NOT IN (subquery)` into an 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 Diagram](https://mermaid.ink/img/pako:eNptkMFKw0AQhl9lnIsHN5iIpyAFI7RWtIUWvTQeNsm0WdzsxNmNbS19d0kDouLcZvh_vo85YMkVYYpry9uy1hLgcZE7AADfFRvRbQ3ZKsfZRZJCEicg3LkKgpjW5_g6JPvJklWOCbx3JPv0ppDL0YYCJHEMZecDNyR9HqJoBNlVH41jaFjo1DDkhw47gpbku3PugaUaugOLXPVHb7LKcWx2VKXwU--X3aS3mzuCh_l0BiwwnQ2qJ6pQ6MR50NZCqOkfJCpsSBptKkwPGGpq-p9VtNadDaiGy4sWowtLvs-s2YWxbozdY4qRbltLkd_7QI2CzBr39qTL5WkfswsKclzShgmepzkqWHDBgRXck_2gYEqt4FaMtgq8dj7yJGaN6gRZms_eJblud3g8Kiw2d2xZMMWzbW0C4fELujuc-g?type=png)

```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 Diagram](https://mermaid.ink/img/pako:eNo9kN9vEzEMx_8V4-ecEBJPFRq6dp2YNKppBcRo-uDmfLuoSVzi3I5S9X9HTdEebX_0_eETOukYZ9gHmdxAucC3W5sAANqNxeXPx4f2fgXtqn14_rUEHWRSYC0-UuEOskz6aZff3_SUoc8SgVwZKdSDxS00zQ3MNxafxvQmIgnKwFBoF9ji9uo2r-jiZHH5X10hyQQuiPJni-crtoCmgWfWSt9uLD4GSjDqSCEcwcdDllfWN9WKr6TSy43FxcBuD05y5lALOAljTGpqCd3zxB10VMiAZMg8ZV-4pv09cj5a3KLByDmS73B2wjJwvHyv457GUNBcNz8o-0s7vTC9pHJH0YcjzrChwyFwo0ctHA3Mg0_7r-TWdb6TVAxYXPOLMHy_t2jgSXZSxMAXDq9cvCMDbfYUDCglbZSz79FUk7X_e8ny4ePhD57PBncvCwmScYbvpsEXxvM_j2SiUA?type=png)

```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` carries over planner statistics, which shortens the slow period after an upgrade.
    

* * *

## Where to Start

When a query is slow, this flowchart points to the right tip:

![Mermaid Diagram](https://mermaid.ink/img/pako:eNpVkltz0zAQRv_Kss_yQC7lkmHKpBAPnSmlrQtDifqwsdexqCy50rppyOS_M7aBpo-Wd79zdqUd5r5gnGFp_SavKAhcf9IOACBbasys38B9y2Gr8RaS5BgulhqvWgeLHxdn89NzmJ_Pz25-LjTeDl0XfdXlaKfxxKwh8n3LTgxZiDk52Bip3q_Cy2OCyJZzMQ8MpbHC4YPG_ZBxOYIkgRuOfVY6WmqcFwWQA-MKfgQfoKY7BqkYmsCFyUm4T40U1rSyPAMxTYSJgqmCo_9yQ_C5HxzHO42LKKYm4QKC30QoKfQ5ZfA1UC4t2f7Hgdv4mdu4WweXgWMFUUhMFJPHHg-jV0_g8SF48m85Pkg3TMHcwNc0zRbXB6DJM9BkqfG0n770oZ-861ZdexsZ7ngbWXr3htbGkRjv_m7hSMGbJ5PJocl0pzGjmoc7hsANd8voc2pyWxBT8-H002dS06XGE5K86jR-eTMQ4d0TbXpAS4-WGlPuykvecIDc27Z2EcgN65_13N55rOC1grcab1FhzaEmU-Bsh1Jx3T3XgktqraAaTr5TMN29x66m9E5Sqo3d4gwTahrLSdxG4VrBiTXu7gvlWf-deicKNGa89gzfTjUquPIrL17BZ7YPLCYnBfNgyCqI5GISOZgSVQ_JzO_OZTRtHnG_V7haf_TWB5zhi01lhHH_B8kgDbE?type=png)

## 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.

---

*Published via [ZyVOP](https://zyvop.com/10-ways-to-speed-up-slow-sql-queries-rmpem?utm_source=hashnode&utm_medium=crosspost&utm_campaign=syndication) — Write once in Markdown, auto-backup to GitHub, and syndicate to Dev.to, Medium & Hashnode in 1 click.*
