
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.
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:
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.
-- 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;flowchart LR
A["SELECT *"] --> B["Needs every column"]
B --> C["Index lookup, then fetch each<br/>full row from the table"]
D["SELECT amount"] --> E["Needs one column"]
E --> F["Answered from the index alone<br/>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.
flowchart TD
A["WHERE EXTRACT(YEAR FROM order_date) = 2026"] --> B["Engine computes the function<br/>for every row"]
B --> C["Index on order_date can't be searched:<br/>full scan"]
D["WHERE order_date in a range<br/>2026-01-01 up to 2027-01-01"] --> E["Column stays bare"]
E --> F["Index seek to the range:<br/>reads only matching rows"]Slow (non-sargable) | Fast (sargable) |
|---|---|
|
|
|
|
|
|
|
|
| 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:
CREATE INDEX idx_customers_email_lower ON customers (LOWER(email));Other sargability traps:
Prefix
LIKEin PostgreSQL: a plain B-tree index supportsLIKE 'abc%'only with theCcollation, or when built withtext_pattern_ops. ForLIKE '%abc%', use a trigram index (CREATE EXTENSION pg_trgm;thenCREATE INDEX ... USING gin (col gin_trgm_ops)).Mismatched types: comparing a text column to a number, or a
VARCHARcolumn to anNVARCHARparameter in SQL Server, can make the engine convert the column instead of the value. Match types exactly.ORacross different columns: some engines can't use one index for it. If the plan shows a scan, tryUNION ALLof two indexed queries. PostgreSQL 18 handles moreORconditions 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.
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"]
endCREATE 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:
CREATE INDEX idx_orders_pending ON orders (order_date) WHERE status = 'pending';Indexes aren't free. Each one slows
INSERT,UPDATE, andDELETEand uses disk space. In PostgreSQL,pg_stat_user_indexes.idx_scan = 0can reveal unused ones (but keep indexes that enforce unique constraints).On live systems, use
CREATE INDEX CONCURRENTLYin 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.
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:
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<br/>order_date order"] --> B3["Return"]
endTwo more rules of thumb:
Leftmost prefix: an index on
(a, b)reliably serves filters ona, or onaandb, but not onbalone. Some engines can "skip scan" in limited cases (PostgreSQL 18, Oracle, MySQL 8), mainly whenahas few distinct values, so don't depend on it.Covering indexes: add the selected columns so the query never touches the table (
INCLUDEin PostgreSQL 11+ and SQL Server):
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 | Optimizers often push them down, but not always | Use |
| Forces a sort or hash to remove duplicates | Use |
| Often masks a join that fans out | Fix the join or filter |
| Sorting work that's usually discarded | Remove it, and sort once at the end |
No | Returns far more rows than anyone reads | Add |
-- 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 aggregating7. 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.
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-- 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:
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.
-- 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);flowchart LR
A["COUNT(*) > 0"] --> B["Finds and counts<br/>every matching row"]
C["EXISTS"] --> D["Stops at the first<br/>matching row"]For "customers with no orders," prefer NOT EXISTS over NOT IN:
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.
flowchart LR
subgraph B["N+1: 101 round trips"]
B1["1 query:<br/>get 100 customers"] --> B2["100 more queries:<br/>one per customer's orders"]
end
subgraph G["Fixed: 1 round trip"]
G1["One JOIN or IN query<br/>returns all the orders"]
end-- 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.
flowchart TD
A["EXPLAIN ANALYZE shows estimated rows<br/>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,<br/>skewed data, or rewrite the query"]ANALYZE orders;Run
ANALYZEafter bulk loads or large deletes. PostgreSQL's autovacuum analyzes tables automatically, but it can lag behind big changes.Heavy
UPDATEandDELETEactivity 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_upgradekeeps planner statistics, so plans don't degrade while the firstANALYZEruns after an upgrade.
Where to Start
When a query is slow, this flowchart points to the right tip:
flowchart TD
S["Slow query"] --> P["Run EXPLAIN ANALYZE"]
P --> Q1{"Big sequential scan with<br/>a selective filter?"}
Q1 -- Yes --> F1["Add an index or make the predicate<br/>sargable: tips 3, 4, 5"]
Q1 -- No --> Q2{"Estimated rows far<br/>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<br/>pagination: tips 5, 7"]
Q3 -- No --> Q4{"Same query repeated<br/>many times?"}
Q4 -- Yes --> F4["Batch or join: tip 9"]
Q4 -- No --> F5["Fetch fewer columns and rows:<br/>tips 2, 6, 8"]Dialect Differences
Task | PostgreSQL | MySQL | SQL Server |
|---|---|---|---|
See the actual plan |
|
| Actual Execution Plan, or |
Refresh statistics |
|
|
|
Covering index |
| Add the columns to the index |
|
Index on an expression | Expression index | Functional index (8.0.13+) | Computed column, then index it |
Limit rows |
|
|
|
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.
Comments(0)
Join the discussion by logging into your account.
No comments yet. Be the first to comment!