How to Optimize Queries with Index Condition Pushdown
Push WHERE predicates into the storage engine with MySQL ICP, mirror the win in PostgreSQL with partial indexes, and prove both with EXPLAIN.
On this page
Introduction
A composite index on (tenant_id, status, created_at) answers range scans efficiently, but a query with additional predicates, say amount above a threshold or a flag check, historically forced the database into an expensive habit: for every index entry matching the prefix, fetch the complete row from the heap, then apply the remaining predicates server-side and discard most rows. The fetch is the cost. Each one is a random read, and on cold or large tables random reads dominate query time. Index condition pushdown, MySQL’s ICP, moves the remaining predicate evaluation down into the storage engine, which can test it against index columns before fetching the row. PostgreSQL approaches the same shape differently: its planner applies index conditions natively, and partial indexes bake predicates into the index itself. This tutorial diagnoses the row-lookup pattern, designs indexes that make predicates pushable, verifies ICP in the execution plan, and translates the whole technique to PostgreSQL so the concept is portable even though the feature name is not.
The row-lookup tax
Understand the cost being eliminated. An index entry is small and stored in a sorted structure, so scanning thousands of entries is sequential and cheap. The heap row behind an entry is elsewhere on disk, and fetching it is a random read. A query filtering orders for one tenant with status pending and amount above one hundred, using an index on (tenant_id, status), matches perhaps ten thousand entries, fetches ten thousand full rows, and returns fifty. Ten thousand random reads produced fifty rows. The server-layer WHERE evaluation happens after the fetch, which is the entire problem: the predicate that could have filtered to fifty rows runs too late to save the ten thousand fetches. This shape shows up clearly in handler counters: Handler_read_key counts index lookups while Handler_next and Handlerrnd read rows sequentially after the initial positioning, and a large ratio of row reads to returned rows is the signature. EXPLAIN ANALYZE shows the same discrepancy as rows examined versus rows sent, and that gap is the optimization budget.
Make predicates pushable
ICP applies only to predicates over columns present in the index. The design move is therefore to extend the composite index so filtering columns, not just join and range columns, live inside it. Order matters: equality predicates first, then the range column last, because a range on an earlier column prevents the index from constraining later columns.
-- before: status filter evaluated after row fetch
CREATE INDEX idx_orders_tenant_status ON orders (tenant_id, status);
SELECT id, total_cents FROM orders
WHERE tenant_id = 42 AND status = 'pending' AND total_cents > 10000;
-- after: total_cents lives in the index, filter is pushable
CREATE INDEX idx_orders_tenant_status_total
ON orders (tenant_id, status, total_cents);
With the extended index, the engine evaluates total_cents > 10000 against the index entry itself, fetches only qualifying rows, and the handler counters drop accordingly. The trade is index width: each added column increases index size and slows writes to that index, so push the columns that filter aggressively, not every column that appears in any WHERE. Queries selecting additional columns beyond the index can still benefit; ICP is about filtering, and index-only scans, covering the SELECT list too, are a further step with a different cost calculus.
Verify with EXPLAIN and handlers
Verification is two measurements, not intuition. First, the plan: the Extra column of EXPLAIN must show Using index condition for the table, which states that ICP is active for this access. Second, the counters: run the query with the session handler counters reset and compare row reads before and after the index change.
EXPLAIN SELECT id, total_cents FROM orders
WHERE tenant_id = 42 AND status = 'pending' AND total_cents > 10000;
-- Extra: Using index condition
FLUSH STATUS;
SELECT id, total_cents FROM orders
WHERE tenant_id = 42 AND status = 'pending' AND total_cents > 10000;
SHOW SESSION STATUS LIKE 'Handler%';
The Handler counters before the change show five-figure reads for a fifty-row result; after, they fall to near the result size. Keep both plans in the migration notes, because plan regressions after upgrades or statistics changes silently re-disable optimizations, and a CI query-plan assertion on Extra contents catches it. ICP can also be toggled per session with optimizer_switch flags for A/B measurement, which isolates its contribution from the index change itself.
The PostgreSQL translation
PostgreSQL does not need the feature because its index scans already evaluate index conditions during the scan, and it offers a stronger tool for the same problem shape: the partial index, which stores only rows matching a predicate. For the hot subset of pending orders, a partial index is smaller than any composite equivalent and answers the exact query from a narrower structure.
CREATE INDEX idx_orders_pending_large
ON orders (tenant_id, created_at)
WHERE status = 'pending' AND total_cents > 10000;
EXPLAIN ANALYZE SELECT id, total_cents FROM orders
WHERE status = 'pending' AND total_cents > 10000
AND tenant_id = 42;
-- Index Scan using idx_orders_pending_large
The planner matches the query predicate to the index predicate at planning time, so the win arrives by construction rather than by engine evaluation. Partial indexes excel when a small, stable subset of rows dominates query traffic: pending work queues, active accounts, unarchived records. The discipline is keeping the index predicate and the query predicate textually aligned enough for the planner to prove implication, and re-checking with EXPLAIN after any query refactor, since a rewritten predicate that no longer implies the index predicate silently reverts to a full scan.
Write-side costs and when not to bother
Every optimization here enlarges or multiplies indexes, and indexes are not free on the write path. An extended composite index adds width to every insert and every update of an indexed column; a partial index is cheap for rows outside the predicate but adds a check to every write. The decision procedure is read-write arithmetic: measure the query frequency times the row-lookup savings, and weigh it against write frequency times the added index maintenance. Skip the work when the query is rare, when the examined-to-sent ratio is small, or when the table fits comfortably in memory, where random reads are cache hits and the row-lookup tax is theoretical. The pattern also matters less on analytical workloads with bitmap scans, which batch heap fetches and reorder them into something closer to sequential. ICP and partial indexes shine on operational tables: queues, dashboards, and administrative filters that run constantly against large, mostly-cold data.
Roll into CI as plan assertions
Execution plans drift: upgrades change defaults, statistics shift after bulk loads, and a refactored WHERE clause stops matching a partial index predicate. The durable practice is asserting plans in CI for the queries that matter. Store the expected plan shape, index name used and scan type, for a set of canonical queries, and diff actual EXPLAIN output against expectations on every release. For MySQL, assert Using index condition or the chosen index in the Extra and key columns; for PostgreSQL, assert the index name in the plan node and the absence of a Seq Scan on tables above a size threshold. These assertions turn silent plan regressions into build failures, which is the only reliable defense, because nobody watches handler counters by hand. Keep the set small, ten to twenty queries that dominate load, gathered from pg_stat_statements or the slow log rather than guessed.
-- PostgreSQL: capture and compare
EXPLAIN (FORMAT JSON) SELECT ... ;
-- assert: Plan->Relation Name->Index Name = idx_orders_pending_large
Common pitfalls
- Range column placed early. A leading range frees later columns from constraint; equalities first, range last.
- Pushing unselective columns. Width costs writes while the predicate filters nothing; push what discriminates.
- Reading EXPLAIN but not counters. The plan states ICP is possible; handler counters prove it paid.
- Partial predicate drift. A refactored query that no longer implies the index predicate silently reverts to full scans.
- Optimizing in-memory tables. Random reads that are cache hits cost little; the tax is real on cold or oversized data.
- Untracked plan regressions. Upgrades and statistics shifts re-disable optimizations quietly; CI plan assertions catch them.
Conclusion
The row-lookup tax, thousands of random heap reads to return fifty rows, is diagnosed with EXPLAIN and handler counters, and both engines offer a precise fix. On MySQL, extend composite indexes so filtering predicates live in the index, enable and verify index condition pushdown through Using index condition and a falling Handler read count. On PostgreSQL, prefer partial indexes for hot subsets, which encode the predicate at index definition and win by construction. Order composite columns equalities first and range last, weigh the write-side cost of index width, and capture the winning plans as CI assertions so upgrades and refactors cannot silently give the tax back. The concept, evaluate predicates before paying for the row, ports to any engine; only the feature names are vendor-specific.
Sources: MySQL: index condition pushdown, PostgreSQL: indexes overview, PostgreSQL: partial indexes.
FAQ
- What exactly does index condition pushdown change?
- Without ICP, MySQL reads the full row for every index entry matching the leading columns, then applies the rest of WHERE server-side. With ICP, the remaining predicates are evaluated on index columns first, so full-row lookups happen only for rows that pass.
- Does PostgreSQL have index condition pushdown?
- PostgreSQL evaluates index conditions inside its index scans as a core behavior and offers partial indexes with a WHERE clause, which is a stronger form of the same idea. The MySQL-specific feature name does not apply, but the optimization goal is identical.
- When does ICP not help?
- When the pushed predicate is unselective, when the query already covers its columns fully in the index, or when all WHERE columns are index prefix columns, in which case there is nothing left to push down.
Report a problem with this articleOpens a pre-filled issue on GitHub.