Skip to content

Lesson 16 of 29Indexes and query performance

Why the Database Ignored Your Index

Find out why a query scans the whole table despite a perfectly good index, and fix it with sargable predicates, matching types, fresh statistics and the right index.

22 min read0/5 questions

You added an index on orders.created_at last sprint. Today the daily revenue dashboard still takes eight seconds, and EXPLAIN says Seq Scan on orders. The index exists, it is valid, and the database is not using it. This happens to every backend engineer, and the cause is almost never a planner bug. Either the query is written in a shape the index cannot serve, or the planner has looked at the numbers and decided, often correctly, that reading the whole table is cheaper. This lesson teaches you to tell those two apart and fix each one.

An index can only answer the question it was built for

As you saw in How indexes work, a B-tree index is a sorted list of column values, each pointing at a row. The database can use it in a small number of ways: jump to one value (=), walk a range (<, >, BETWEEN, a prefix), or read in order to avoid a sort. Every one of those relies on the index being sorted by the raw column value.

So the planner asks one question about each condition in your WHERE clause: can I turn this into "seek to X, then walk forward until Y" on some index? A condition that can be answered that way is called sargable, from "Search ARGument ABLE". A condition that cannot is evaluated row by row, and the index is no help at all.

Here is the dashboard query that started this lesson:

-- Postgres: created_at is timestamptz, indexed
SELECT sum(total_cents) FROM orders
WHERE created_at::date = '2026-03-14';

The index holds created_at values, sorted. It does not hold created_at::date. To know which rows have that date, Postgres would have to compute the cast for every entry. There is no seek point, so it scans.

Seeking a range versus testing every entry
03-13 22:10
0
03-13 23:55
1
03-14 00:20
2
03-14 09:05
3
03-14 18:40
4
03-15 00:05
5
03-15 07:30
6
predicate = none yetentries_read = 0

The index on created_at: timestamps in sorted order, each pointing at a row. Shown as month-day and time.

1/4

The fix is to move the computation to the other side of the comparison, so the column stands alone:

SELECT sum(total_cents) FROM orders
WHERE created_at >= '2026-03-14' AND created_at < '2026-03-15';

Use a half-open range, >= start and < next day. BETWEEN '2026-03-14' AND '2026-03-14 23:59:59' silently drops anything in the last second, and a timestamptz has microseconds.

Run both versions on 100,000 orders. SQLite's EXPLAIN QUERY PLAN uses the words SCAN (read everything) and SEARCH (seek with an index):

Pythonsargable.py
import random, timefrom shopdb import connectdb = connect()random.seed(7) db.execute("""CREATE TABLE big_orders ( id INTEGER PRIMARY KEY, customer_id INTEGER NOT NULL, status TEXT NOT NULL, created_at TEXT NOT NULL, total_cents INTEGER NOT NULL)""")db.executemany("INSERT INTO big_orders VALUES (?, ?, ?, ?, ?)", ( (i, random.randint(1, 5000), random.choice(["shipped", "paid", "pending"]), time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(1767225600 + i * 260)), random.randint(500, 50000)) for i in range(1, 100_001)))db.execute("CREATE INDEX ix_big_orders_created ON big_orders (created_at)") def plan(sql): for row in db.execute("EXPLAIN QUERY PLAN " + sql): print(" plan:", row[3]) def timed(label, sql): start = time.perf_counter() total = db.execute(sql).fetchone()[0] ms = (time.perf_counter() - start) * 1000 print(f"{label}: total={total} {ms:.2f} ms") plan(sql) timed("function on column", """SELECT sum(total_cents) FROM big_orders WHERE date(created_at) = '2026-03-14'""")timed("range on column ", """SELECT sum(total_cents) FROM big_orders WHERE created_at >= '2026-03-14' AND created_at < '2026-03-15'""")
Output
Press Run (⌘ Enter) to see what happens.

Same answer, very different work. The range query reads a few hundred index entries; the function version reads all 100,000 rows.

The same rule covers arithmetic and string functions. Each of these defeats a plain index on the column, and each has a sargable rewrite:

Not sargableSargable rewrite
WHERE id + 1 = 5000WHERE id = 4999
WHERE price_cents / 100 > 50WHERE price_cents > 5000
WHERE extract(year FROM created_at) = 2026WHERE created_at >= '2026-01-01' AND created_at < '2027-01-01'
WHERE substr(sku, 1, 3) = 'LAP'WHERE sku LIKE 'LAP%' (with a prefix-capable index, see below)
WHERE coalesce(deleted_at, 'infinity') > now()WHERE deleted_at IS NULL OR deleted_at > now()

When you cannot rewrite the query, for example because lower(email) is the real business rule, build an expression index that stores exactly that expression, as you saw in Composite, covering and partial indexes. The query must then use the identical expression, lower(email) = lower($1), or it will not match.

Hidden functions: casts, types and collations

The worst cases are the ones where you did not write a function at all. The database inserted one for you.

Type mismatches. If the column and the value have different types, one side gets converted. If the database converts the value, the index still works. If it converts the column, every row is converted and the index is useless.

  • In Postgres, WHERE bigint_id = 42.0 compares against a numeric, so the bigint column is cast to numeric and the B-tree on bigint cannot be used. A driver that binds a Python Decimal or a JavaScript float as numeric causes the same thing. The cure is to bind the right type.
  • In MySQL, comparing a VARCHAR column with a number, WHERE phone = 5551234, converts every phone to a number. The index on phone is ignored, and you also get wrong matches, because '5551234abc' converts to 5551234.
  • In MySQL, joining two string columns with different character sets or collations (one table utf8mb4_0900_ai_ci, an older one utf8mb3_general_ci) forces a conversion on one side, and the index on that side cannot be used for the join. This shows up after merging schemas from two services.

Collations. An index is sorted under one collation. A query that compares under a different one cannot use that order. SQLite makes this easy to see, because COLLATE NOCASE is a per-comparison choice:

Pythonhidden_functions.py
import randomfrom shopdb import connectdb = connect()random.seed(3) db.execute("CREATE TABLE accounts (id INTEGER PRIMARY KEY, customer_id INTEGER, email TEXT)")db.executemany("INSERT INTO accounts VALUES (?, ?, ?)", ((i, random.randint(1, 5000), f"user{i}@example.com") for i in range(1, 50_001)))db.execute("CREATE INDEX ix_accounts_email ON accounts (email)")db.execute("CREATE INDEX ix_accounts_customer ON accounts (customer_id)") def plan(label, sql): detail = " / ".join(r[3] for r in db.execute("EXPLAIN QUERY PLAN " + sql)) print(f"{label:<26} {detail}") plan("plain equality", "SELECT * FROM accounts WHERE email = 'user7@example.com'")plan("arithmetic on column", "SELECT * FROM accounts WHERE customer_id + 0 = 7")plan("cast on column", "SELECT * FROM accounts WHERE CAST(customer_id AS TEXT) = '7'")plan("different collation", "SELECT * FROM accounts WHERE email = 'USER7@example.com' COLLATE NOCASE")plan("lower() on column", "SELECT * FROM accounts WHERE lower(email) = 'user7@example.com'")plan("LIKE prefix", "SELECT * FROM accounts WHERE email LIKE 'user7@%'")plan("LIKE leading wildcard", "SELECT * FROM accounts WHERE email LIKE '%@example.com'")plan("OR across two columns", "SELECT * FROM accounts WHERE customer_id = 7 OR email = 'user9@example.com'")plan("not equal", "SELECT * FROM accounts WHERE customer_id <> 7") db.execute("CREATE INDEX ix_accounts_email_nocase ON accounts (email COLLATE NOCASE)")print("-- after adding an index sorted under NOCASE:")plan("different collation", "SELECT * FROM accounts WHERE email = 'USER7@example.com' COLLATE NOCASE")plan("LIKE prefix", "SELECT * FROM accounts WHERE email LIKE 'user7@%'")
Output
Press Run (⌘ Enter) to see what happens.

Look at the first block of results. Arithmetic, a cast, a different collation and lower() all turn SEARCH into SCAN. The fix in each case is either to compare the bare column with a value of the same type, or to create an index on the exact expression or collation the query uses. After adding the NOCASE index, both the case-insensitive equality and the LIKE prefix become searches.

LIKE, prefixes and leading wildcards

Two different problems hide under LIKE.

A leading wildcard (LIKE '%@example.com' or LIKE '%laptop%') cannot use a B-tree in any database. A sorted list helps you find things that start with something; it says nothing about what they end with. You have three real options in Postgres:

  • pg_trgm with a GIN index. It indexes every three-character fragment, so it can serve LIKE and ILIKE with wildcards anywhere, and similarity search for typos. Short patterns (one or two characters) still scan.
  • Full-text search when users search for words in prose. That is a different tool with its own lesson, Full-text search in the database.
  • Store the part you search on, such as an email_domain column, and index it normally.
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE INDEX CONCURRENTLY ix_products_name_trgm
    ON products USING gin (name gin_trgm_ops);
 
SELECT id, name FROM products WHERE name ILIKE '%headphone%';

A prefix (LIKE 'user7@%') is a range in disguise: everything from 'user7@' up to just before 'user7A'. It should be able to use a B-tree, but only if the index sorts the same way the comparison does. That is where the dialects trip people up:

  • Postgres can use a plain B-tree for LIKE 'abc%' only when the column uses the C collation. Most databases are created with a locale such as en_US.UTF-8, whose ordering rules are not simple byte order, so the planner cannot turn the prefix into a range. Create the index with the pattern operator class: CREATE INDEX ... ON customers (email text_pattern_ops) (varchar_pattern_ops for varchar). Keep the normal index too if you also need < and ORDER BY under the locale.
  • SQLite LIKE is case-insensitive for ASCII by default, so it can use an index only when that index is declared COLLATE NOCASE, which is what the runnable block showed. GLOB 'user7@*', which is case-sensitive, uses a normal index.
  • MySQL uses an ordinary index for a constant prefix LIKE 'abc%', as long as the collation of the column and the pattern agree.

OR, not-equal and NOT IN

A single B-tree serves one access path. A condition like customer_id = 7 OR email = 'x' needs two paths, so a planner that can only pick one index has to scan.

Modern planners can do better. Postgres builds a BitmapOr: one Bitmap Index Scan per branch, combines the matching row locations into one bitmap, then visits the table once. SQLite does the same idea under the name MULTI-INDEX OR, which you saw in the runnable block. The catch is that every branch needs a usable index. If one branch is notes LIKE '%refund%', the whole query scans.

When the planner will not combine them, rewrite the OR as a UNION so each half gets its own plan:

SELECT * FROM orders WHERE customer_id = 7
UNION
SELECT * FROM orders WHERE coupon_code = 'SPRING26';

<> and NOT IN are a different story. "Every value except 7" is two ranges covering almost the whole index, so a scan is usually the right plan, and Postgres does not use a B-tree for <> at all. If one value is rare and you keep asking for "everything except the rare one", flip the question. A queue that asks WHERE status <> 'done' is really asking for the few pending rows, so write WHERE status IN ('pending', 'running') and support it with a partial index WHERE status <> 'done'. Remember also that NOT IN (subquery) returns no rows at all when the subquery yields a NULL; prefer NOT EXISTS, which also plans well as an anti-join.

When a full scan is the right answer

Sometimes the planner ignores your index because it is smart. An index lookup is not free. For each matching entry the database jumps to the table to fetch the row, and those jumps land on scattered pages. A sequential scan reads pages in order, which disks and operating systems are very good at.

Postgres models this with random_page_cost (default 4.0) against seq_page_cost (1.0). Roughly: if a query will return more than a few percent of the table, or the table fits in a handful of pages, a scan wins. Three situations where a seq scan is correct:

  • Small tables. A 200-row countries table fits in a couple of pages. Reading them is faster than descending an index.
  • Low selectivity. WHERE status = 'shipped' when 60% of orders are shipped. You will visit most pages anyway.
  • You asked for most of the table. Reports, exports and count(*) without a filter.

You can feel this in SQLite by forcing each plan with INDEXED BY and NOT INDEXED, two hints that exist mainly for experiments like this one:

Pythonscan_on_purpose.py
import random, timefrom shopdb import connectdb = connect()random.seed(1) statuses = ["shipped"] * 6 + ["paid"] * 3 + ["pending"]db.execute("CREATE TABLE big_orders (id INTEGER PRIMARY KEY, status TEXT, total_cents INTEGER)")db.executemany("INSERT INTO big_orders VALUES (?, ?, ?)", ((i, random.choice(statuses), random.randint(500, 50000)) for i in range(1, 100_001)))db.execute("CREATE INDEX ix_big_orders_status ON big_orders (status)") def best_ms(sql, runs=3): best = float("inf") for _ in range(runs): start = time.perf_counter() db.execute(sql).fetchall() best = min(best, time.perf_counter() - start) return best * 1000 for status in ["pending", "shipped"]: share = db.execute("SELECT avg(status = ?) FROM big_orders", (status,)).fetchone()[0] via_index = best_ms(f"SELECT sum(total_cents) FROM big_orders INDEXED BY ix_big_orders_status WHERE status = '{status}'") via_scan = best_ms(f"SELECT sum(total_cents) FROM big_orders NOT INDEXED WHERE status = '{status}'") print(f"{status:<8} {share:5.0%} of rows index {via_index:5.1f} ms full scan {via_scan:5.1f} ms")
Output
Press Run (⌘ Enter) to see what happens.

For the rare status, the index wins. For the common one, the full scan wins, even with everything in memory where random access is cheap. On real disks the gap is far larger. (The f-string here only inserts a hard-coded status for the experiment; real code uses parameters.)

If your index is ignored on a large fraction of rows, the fix is not to force it. Ask whether the query should be returning that many rows, or whether a covering index could answer it from the index alone, which removes the expensive table jumps.

Stale statistics and correlated columns

The planner does not count rows when it plans. It estimates them from statistics: per column, the number of distinct values, the most common values with their frequencies, a histogram, and the fraction of NULLs. ANALYZE builds these from a random sample of about 300 × default_statistics_target rows, so 30,000 rows with the default target of 100.

Autovacuum runs ANALYZE for you once enough rows change (by default, 50 rows plus 10% of the table). That threshold is the trap. Three common ways statistics go wrong:

  • Right after a bulk load or a big backfill. The table went from empty to ten million rows a minute ago, and the planner still thinks it is empty. Run ANALYZE table_name as the last step of every bulk load or migration that rewrites data.
  • Huge tables with recent hot data. On a billion-row table, 10% is 100 million changes. Today's rows may not be in the histogram yet, so WHERE created_at > now() - interval '1 hour' is estimated at almost zero rows. Lower autovacuum_analyze_scale_factor for that table.
  • Skewed columns. If one tenant owns 40% of the rows, raise the target for that column so the most-common-values list captures it: ALTER TABLE orders ALTER COLUMN tenant_id SET STATISTICS 1000; then ANALYZE orders.

Correlated columns are a subtler failure. The planner assumes columns are independent. For WHERE city = 'Paris' AND country = 'FR' it multiplies the two selectivities and badly underestimates, because every Paris row is in France. Underestimates lead to nested loops over far more rows than expected. Postgres extended statistics fix it:

CREATE STATISTICS st_addresses_city_country (dependencies, ndistinct, mcv)
    ON city, country FROM addresses;
ANALYZE addresses;

You find these problems by comparing estimated and actual row counts in EXPLAIN ANALYZE, which is the main skill of the next lesson, Reading EXPLAIN and EXPLAIN ANALYZE.

Prepared statements: generic and custom plans

ORMs and drivers often use prepared statements: the SQL is parsed once, then executed many times with different parameters. In Postgres, the first five executions get a custom plan built for the actual parameter values. After that, Postgres builds a generic plan that ignores the values, and keeps using it if its estimated cost is not much worse than the custom plans were.

That is usually great. It goes wrong on skewed data. Imagine WHERE status = $1 where 'pending' is 0.1% of rows and 'shipped' is 70%. The generic plan picks one strategy for both, so one of them gets the wrong one. The symptom is a query that is fast in psql (where you typed a literal) and slow from the application (which sends a parameter).

The setting plan_cache_mode controls this. auto is the default; force_custom_plan re-plans every execution, which costs a little planning time and fixes skew. Set it per role or per transaction for the affected queries, not globally.

Finding unused and missing indexes

Indexes that nobody reads still cost you on every write and in every backup. Postgres counts index usage:

SELECT s.relname        AS table_name,
       s.indexrelname   AS index_name,
       s.idx_scan,
       s.last_idx_scan,                                  -- Postgres 16+
       pg_size_pretty(pg_relation_size(s.indexrelid))    AS size
FROM pg_stat_user_indexes s
JOIN pg_index i ON i.indexrelid = s.indexrelid
WHERE s.idx_scan = 0
  AND NOT i.indisunique                                  -- unique indexes enforce rules
ORDER BY pg_relation_size(s.indexrelid) DESC;

Before dropping anything, check three things. The counters are per server, so an index unused on the primary may be busy on a read replica. They reset with pg_stat_reset() and some failovers, so look at how long they have been collecting. And unique indexes enforce constraints even with idx_scan = 0.

Missing indexes show up as big tables with lots of sequential reads. pg_stat_user_tables has seq_scan and seq_tup_read; a large seq_tup_read / seq_scan on a big table means full scans of it are common. Then pg_stat_statements tells you which queries spend the most total time, which is where to look first.

When you add the index in production, build it without blocking writes:

CREATE INDEX CONCURRENTLY ix_orders_created_at ON orders (created_at);

CONCURRENTLY cannot run inside a transaction block, so most migration tools need a flag to run it outside one. It takes longer and scans the table twice. If it fails (a deadlock, a unique violation, a cancelled statement), it leaves behind an INVALID index that slows writes and serves no reads. Find it with SELECT indexrelid::regclass FROM pg_index WHERE NOT indisvalid;, then DROP INDEX CONCURRENTLY and retry.

Practice

Quick check
orders.created_at is a timestamptz with a B-tree index. Which filter can use it to find orders from March 2026?
Need a nudge? A hint rules out a wrong answer.
Predict the outputPython

Each line prints the first word of the plan. What is the output?

import sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE t (id INTEGER PRIMARY KEY, n INTEGER, s TEXT)")
db.execute("CREATE INDEX ix_n ON t (n)")
db.execute("CREATE INDEX ix_s ON t (s)")
for where in ["n = 5", "n * 2 = 10", "s LIKE 'ab%'", "s GLOB 'ab*'"]:
  row = db.execute("EXPLAIN QUERY PLAN SELECT * FROM t WHERE " + where).fetchone()
  print(row[3].split()[0])
Need a nudge? Hints walk you through it.
Match the pairs0/5 matched

Match each slow query to the most direct fix.

Choose an item, then its match on the other side.
Quick check
A 5-million-row orders table has an index on status. WHERE status = 'shipped' matches 70% of rows and Postgres uses a Seq Scan. What should you do?
Need a nudge? A hint rules out a wrong answer.
Put it in order5 steps

Order the steps for safely adding a missing index to a busy production table.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
sargable
A condition the database can answer by seeking an index, typically the bare column compared with a constant or a range.
expression index
An index on a computed value such as lower(email). Queries must use exactly the same expression to benefit.
text_pattern_ops
A Postgres operator class that lets a B-tree serve LIKE 'prefix%' on columns with a non-C collation.
pg_trgm
A Postgres extension that indexes three-character fragments, so GIN indexes can serve LIKE and ILIKE with wildcards anywhere.
BitmapOr
A Postgres plan step that combines the results of several index scans so an OR across indexed columns avoids a full scan.
extended statistics
Statistics on a group of columns (CREATE STATISTICS) that tell the planner when columns are correlated.
generic plan
A cached plan for a prepared statement that ignores the parameter values. Can be wrong for skewed data.