
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.
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 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.
-- 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;
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.
| 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) | LIKE 'Son%' only if "starts with" is what you need. For "ends with" or "contains", use a trigram index |
| WHERE LOWER(email) = '[email protected]' | 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:
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. That operator class serves pattern matching and equality but not ordinary comparisons like<and>, so you may need a second, default index. ForLIKE '%abc%', use a trigram index (CREATE EXTENSION pg_trgm;thenCREATE 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
VARCHARcolumn to anNVARCHARparameter. Either way the index may stop working. (PostgreSQL usually raises an error instead.) Match types exactly.ORacross different columns: many engines can combine separate indexes (PostgreSQL's bitmap OR, MySQL's index merge), and PostgreSQL 18 handles moreORcases with an index. If the plan still shows a scan, try aUNIONof two indexed queries. Don't useUNION ALLhere 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.
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:
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 manyUPDATEs) and uses disk space. In PostgreSQL,pg_stat_user_indexes.idx_scan = 0can reveal unused ones once statistics have been collected for long enough (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 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.
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:
The order of the range and sort columns matters. For WHERE customer_id = 42 AND amount > 500 ORDER BY order_date:
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 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 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 |
-- 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.
-- 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. 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.
-- 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);
(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:
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.
-- 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.
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_upgradecarries 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:
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 — Write once in Markdown, auto-backup to GitHub, and syndicate to Dev.to, Medium & Hashnode in 1 click.
About the author
- One platform to write, cross-post to Dev.to, Medium, WordPress, Hashnode, and Bluesky, and protect your SEO with canonical links. Zero paywalls and full content ownership.
Comments
Join the discussionNo comments yet. Be the first to comment.





