
When an SQL index is not used, the database has an index on the right column but the optimizer can't match it to your query, so it reads the whole table instead. You did the right thing. You built the index. The query is still slow, and the CPU is still spiking.
This guide moves from the symptom you're seeing, to the causes behind it, to the fixes that make the index work again. It ends with the habits that keep the problem out of production. An index existing and an index being used are two different things. Let's close that gap.
- Wrapping an indexed column in a function like LOWER() hides it from a normal index.
- Leading wildcards ('%term') and type mismatches quietly force full table scans.
- Composite indexes are sorted left to right, so skipping the leftmost column often breaks them.
- EXPLAIN ANALYZE shows whether you get a Seq Scan or an Index Scan.
- Fix it by rewriting the predicate, reordering columns, or indexing the expression, then verify.
- 0:00Intro
- 0:26Index added. Query still crawling.
- 1:09Functions blind the optimizer
- 1:54Wildcards and types force full scans
- 2:38Composite indexes need the leftmost column
- 3:21Ask the database: EXPLAIN ANALYZE
- 4:04Rewrite predicates to be sargable
- 4:53Reorder columns or index the expression
- 5:38Same query. Completely different plan.
- 6:21Make plan checks a habit
- 7:08Same symptom, different cause
- 7:48Why your index gets ignored
- 8:16Your index only helps if used
Index added, query still slow: the symptom
Here's the scene. There's an index on the email column. A query asks for exactly one user by email, but the column is wrapped in LOWER. It returns a single row, and it takes seconds to do it. Meanwhile the server's CPU climbs.
A single-row lookup should be close to instant. When it takes seconds, the database is doing far more work than the result suggests. That gap between a tiny result and a heavy workload is your first clue.
This is what makes it so frustrating. You followed the advice, built the index, and the optimizer walked right past it. It looks like an index problem. It's actually a query problem. Adding an index isn't the finish line. The query has to be written so the index can be used.
- One row returned, seconds spent
- CPU spikes on a simple lookup
- The index exists but is never touched
# idx_users_email exists. Unused.
SELECT * FROM users
WHERE LOWER(email) = 'ana@shop.io';
# One row back. Seconds later. CPU spikes.
Why functions like LOWER() make the index useless
The most common culprit is a function wrapped around the indexed column. Follow what the planner does. It reads LOWER(email). The index stores the raw email values. Those are different expressions, so the keys don't match. With no usable match, the planner falls back to a Seq Scan on users.
A Seq Scan reads every single row. Worse, the database can't search sorted values it doesn't have, so it calculates LOWER for each row in the table, one by one, before comparing. That per-row work is where the CPU spike comes from.
LOWER isn't special. YEAR, CAST, TRIM: any function applied to the column side of the comparison hides that column from a normal index. Your WHERE clause decides whether the index gets used or ignored.
- Planner reads LOWER(email)
- Index stores raw email values
- No match, so it falls back to a Seq Scan
Leading wildcards and type mismatches force full scans
Functions aren't the only trap. Two quieter mistakes do the same damage, and they hide in normal-looking queries. The first is LIKE with a percent sign at the start, such as '%term'. The second is comparing a text column, like phone, to a number.
Why does a leading wildcard hurt? An index is sorted, like a dictionary. If you don't know how the word starts, you can't jump to the right page, so you read every page. '%term' could match anywhere, which means nothing can be skipped.
The type mismatch is sneakier. To compare text with a number, the engine may convert the column on every row. That's a function in disguise, with the same result as wrapping the column in CAST. Your index can be ignored without any visible function in the query.
- '%term' gives the index no starting point
- Text column vs numeric value can trigger a hidden per-row cast
# Trap 1: leading wildcard
WHERE name LIKE '%phone'
# Trap 2: phone is VARCHAR, value is a number
WHERE phone = 5551234
Composite index column order: the leftmost rule
Now the one that catches experienced developers. You built a multi-column index and it still gets ignored, because column order matters more than most people expect. A composite index is a nested sort: by the first column, then by the next one within that.
Take an index on country, then city. It's sorted by country first, and by city only inside each country. Filter by country and the index works. Filter only by city and you've skipped the leftmost column. City values are scattered across every country, so the index often becomes useless.
Think of a phone book sorted by surname. It's great for finding a surname. It can't help you find everyone whose first name is Lyon. Order your index columns to match how your queries actually filter.
- Sorted by country, then city within country
- Filtering on city alone skips the leftmost column
CREATE INDEX idx_loc
ON stores (country, city);
# ✓ WHERE country = 'FR'
# ✗ WHERE city = 'Lyon'
How to check if an index is used: EXPLAIN ANALYZE
Stop guessing. Ask the database what it's actually doing. Open psql, put EXPLAIN ANALYZE in front of the slow query, and run it. One command shows the real plan and the real time it took.
In the LOWER(email) example, the answer is immediate: Seq Scan on users. The filter line shows lower(email) being checked against every row. That's the whole problem, confirmed in seconds.
Know what to look for. In Postgres, Seq Scan is the alarm. In MySQL's EXPLAIN, look for type ALL. On a big table, both mean every row was read. When the plan instead says Index Scan or Index Only Scan, your index is doing its job.
- Postgres: Seq Scan means a full read
- MySQL: type ALL means a full read
- Index Scan or Index Only Scan means the index is used
psql shop
Fix 1: rewrite the WHERE clause to be sargable
The first fix costs nothing: rewrite the predicate so the index can search it directly. That's called sargable, short for search-argument-able. The rule is simple. Keep the indexed column bare on one side, and give it a value of a matching type.
Instead of filtering on YEAR(created_at), ask for a date range on the raw created_at column. You get the same rows, but now the index can jump straight to them. Move the transformation to the constant side, so it's computed once instead of once per row. For the phone column, pass a string to match the text type.
Wildcards follow the same logic. 'term%' keeps a starting point and can use the index. '%term' can't. If you truly need contains-style search, use a full-text or trigram index instead.
- Use a range on the raw column, not a function on it
- Match the value's type to the column's type
- Prefer 'term%' over '%term'
# ✗ YEAR(created_at) = 2024
WHERE created_at >= '2024-01-01'
AND created_at < '2025-01-01'
# ✗ phone = 5551234
WHERE phone = '5551234'
Fix 2: reorder columns or index the expression
Sometimes you can't change the query. That's fine. Flip it around and change the index to match the query. There are two moves: reorder the composite index, or index the function itself.
If most queries filter on city alone, put city first. Lead with the column every query filters on, usually an equality filter, with range filters later. If the app always calls LOWER(email), create an expression index on exactly that. The database stores the computed values, already sorted. The expression must match the query exactly.
Then run EXPLAIN ANALYZE again. Before: a Seq Scan, every row read, seconds for one row, CPU spiking. After: an Index Scan that jumps to the matching rows and returns in a blink. No new hardware, no cache. The query and index finally line up.
- Put the always-filtered column first
- Index LOWER(email) if queries use LOWER(email)
- Re-run EXPLAIN ANALYZE to confirm the plan flipped
# Queries filter on city alone?
CREATE INDEX idx_city_country
ON stores (city, country);
# Can't change LOWER(email)?
CREATE INDEX idx_users_email_lower
ON users (LOWER(email));
How to keep slow queries out of production
Fixing it once is good. Never shipping it again is better. Use a repeating loop: write the query, EXPLAIN it before it merges, ship it once the plan looks clean, refresh statistics, and drop unused indexes. Then start again with the next query.
Statistics matter because the optimizer picks plans from its estimates of your data. Stale stats lead to bad estimates and bad plans, so run ANALYZE after big data changes. Unused indexes have a cost too: every insert and update maintains them, and they take disk space. In Postgres, pg_stat_user_indexes shows which ones never get scanned.
One warning. Not every slow query with an index is a sargability problem. If the predicate looks clean, check stale stats, low selectivity, a tiny table, lock waits, or N+1 queries. Wrong row estimates point to stats; a fast plan inside a slow request points elsewhere.
- EXPLAIN every query before merging
- Run ANALYZE after large data changes
- Drop indexes that never get scanned
- Rule out stats, selectivity, locks and N+1 queries
The bottom line
- An index only helps if the query can actually use it.
- Functions, leading wildcards and type mismatches on the column side force full scans.
- Composite indexes need the leftmost column in the filter.
- EXPLAIN ANALYZE tells you the truth: Seq Scan or Index Scan.
- Rewrite the predicate, reorder the index, or index the expression, then verify.
- Keep stats fresh and drop indexes nobody uses.
Quick-fire questions
Why is my SQL index not being used?
Usually the query is written in a way the index can't match. Common causes are a function on the indexed column, a leading wildcard in LIKE, a type mismatch, or skipping the leftmost column of a composite index.
How do I check if a query uses an index?
Run the query with EXPLAIN ANALYZE in Postgres or EXPLAIN in MySQL. A Seq Scan (Postgres) or type ALL (MySQL) means the whole table was read, while Index Scan or Index Only Scan means the index was used.
Does LOWER() in a WHERE clause prevent index use?
With a normal index on the raw column, yes, because the index stores raw values and the query asks for lowercased ones. You can fix this by creating an expression index on LOWER(email) that matches the query exactly.
What does sargable mean in SQL?
Sargable means search-argument-able: the predicate can use an index directly. In practice, that means keeping the indexed column bare on one side of the comparison and moving any transformation to the value side.
Does column order matter in a composite index?
Yes. A composite index is sorted by its first column, then by the next within that. Filtering only on a later column skips the leftmost one, so the index often can't help.
My query looks sargable but is still slow. What else could it be?
Check stale statistics, low selectivity where most rows match, a tiny table, lock waits, or N+1 queries. EXPLAIN ANALYZE helps separate these, since wrong row estimates point to stats and a fast plan inside a slow request points elsewhere.