Sub topic 8
Writing predicates an index can use
This chapter assumes you can read a basic EXPLAIN plan and know how a B-tree index finds a value or a range. It also assumes you know how a composite index orders its columns. The examples use PostgreSQL syntax.
Why the shape of a predicate matters
A B-tree index is sorted by the stored column value. The database can descend the tree only when the query supplies a value or range in that same sorted order. A predicate that meets this condition is called sargable, short for "search ARGument ABLE". Typically it has the form:
indexed_column operator value_that_does_not_depend_on_the_rowThe operator is one the index supports, such as =, <, <=, >, >=, BETWEEN, IN, or IS NULL. If you change the left side, for example by wrapping the column in a function, the index no longer matches. Its entries are sorted by created_at, not by date_trunc('month', created_at). The planner cannot assume the two orderings agree, so it falls back to checking every row.
This is a planner limitation, not a bug. The query still returns correct results. It just reads far more data than it needs to.
The core rule: leave the column bare
Compare two queries for the same January data:
-- Index-friendly: compares the bare column to a range.
SELECT count(*) FROM orders
WHERE created_at >= '2026-01-01' AND created_at < '2026-02-01';
-- Usually not index-friendly: wraps the column in a function.
SELECT count(*) FROM orders
WHERE date_trunc('month', created_at) = '2026-01-01';In the first query the planner can descend to the first entry at or after 2026-01-01, walk forward along the leaf pages, and stop at 2026-02-01. In the second query it would have to compute date_trunc for every row before it could compare anything.
Use half-open ranges for timestamps
Write >= start AND < next_start, not BETWEEN. BETWEEN includes both endpoints. For a timestamptz column, BETWEEN '2026-01-01' AND '2026-01-31' silently excludes everything after midnight on January 31. A half-open range has no such gap and is also sargable.
Common patterns that defeat an index
| Pattern | Why it fails | Index-friendly rewrite |
|---|---|---|
| `date_trunc('day', created_at) = '2026-01-15'` | Function applied to the column | `created_at >= '2026-01-15' AND created_at < '2026-01-16'` |
| `created_at::date = '2026-01-15'` | Cast on the column, and the result depends on the session time zone | Same half-open range |
| `extract(year FROM created_at) = 2026` | Function applied to the column | `created_at >= '2026-01-01' AND created_at < '2027-01-01'` |
| `id + 1 = 43` | Arithmetic on the column | `id = 42` |
| `total_cents * 2 > 10000` | Arithmetic on the column | `total_cents > 5000` |
| `lower(email) = '[email protected]'` | Function applied to the column | Expression index on `lower(email)` |
| `name LIKE '%son'` | Leading wildcard has no sorted prefix | Trigram index, or redesign the search |
| `status <> 'closed'` | Matches most rows, so there is no narrow range | Usually leave it, or use a partial index |
The fix is nearly always algebra. Move the arithmetic or function to the side of the comparison that holds the constant, so the column stands alone.
Arithmetic example
-- Not sargable: the planner must compute total_cents * 2 for every row.
SELECT id FROM orders WHERE total_cents * 2 > 10000;
-- Sargable: same meaning, constant folded to the right.
SELECT id FROM orders WHERE total_cents > 5000;Both queries return the same rows because total_cents is an integer and the multiplication is exact. Be careful with integer division. total_cents / 100 > 50 is not the same as total_cents > 5000, because division truncates. In that case the correct rewrite is total_cents >= 5100.
When you cannot change the query: expression indexes
Sometimes the function is the right thing to ask for. Case-insensitive email lookup is the usual example. Instead of rewriting the query, index the expression:
CREATE INDEX users_lower_email_idx ON users (lower(email));
SELECT * FROM users WHERE lower(email) = '[email protected]';The index stores lower(email) as its sort key, so a query that uses the identical expression can descend the tree. The match is syntactic. lower(email) is covered, but upper(email) and email ILIKE '[email protected]' are not. The function must also be immutable, meaning it always returns the same result for the same input. A function that depends on the session time zone, such as created_at::date on a timestamptz column, is not allowed in an index expression.
Type mismatches and implicit casts
An index on column c matches a comparison only if the planner can compare c itself, in its own type, to the value. If the comparison forces a cast on the column, the index is skipped. Typical causes are:
- Comparing a column to a parameter that the driver sends with a different type, such as a
numericparameter against abigintcolumn. - Joining two columns of different types, such as
integertobigintin some systems, orvarchartotextwith different collations. - Comparing a string column to a number in systems that cast silently, such as MySQL. PostgreSQL usually raises an error instead.
When a query that should use an index does not, check the plan for a Filter: or Index Cond: line that shows a cast such as (customer_id)::numeric. Fix the parameter type, not the index.
Pattern matching with LIKE
LIKE 'abc%' has a fixed prefix, so it is equivalent to a range from abc up to just below abd. A B-tree can serve this only if its sort order matches that range. In PostgreSQL with a non-C collation, the default operator class sorts by locale rules, so prefix matching needs a different operator class:
CREATE INDEX users_email_prefix_idx ON users (email text_pattern_ops);
SELECT * FROM users WHERE email LIKE 'ada%';A pattern with a leading wildcard, such as '%son', has no sorted prefix and cannot use a B-tree at all. For substring search, look at a trigram index (pg_trgm with GIN), which a later chapter on other index types covers.
OR, IN, and negation
col IN (1, 2, 3)is sargable. The planner treats it as several point lookups on the same index.col = 1 OR col = 2on the same column is equivalent and usually handled the same way.a = 1 OR b = 2on different columns needs one index per column. PostgreSQL can combine them with a BitmapOr, but only if both columns are indexed. If one is not, the whole query falls back to a scan.<>,NOT IN, andNOT LIKErarely benefit. They match most of the table, so the planner picks a scan on selectivity grounds even when the predicate is technically indexable.
Predicates and composite indexes
Sargability applies to each column of a composite index separately. Given an index on (customer_id, created_at):
-- Both columns are sargable: seek on customer_id, then range on created_at.
SELECT * FROM orders
WHERE customer_id = 42 AND created_at >= '2026-01-01';
-- created_at is wrapped in a function, so only customer_id narrows the search.
SELECT * FROM orders
WHERE customer_id = 42 AND date_trunc('day', created_at) = '2026-01-01';In the second query the index still helps, because customer_id is bare. The database finds all entries for customer 42 and then applies the function as a filter on those rows. A bad predicate on one column weakens the index. It does not necessarily disable it.
Checking the result in a plan
Do not guess. Build a table large enough that a scan is clearly worse than a seek, then compare the plans.
CREATE TABLE orders (
id bigint PRIMARY KEY,
customer_id bigint NOT NULL,
status text NOT NULL,
created_at timestamptz NOT NULL,
total_cents integer NOT NULL
);
INSERT INTO orders (id, customer_id, status, created_at, total_cents)
SELECT g,
(random() * 50000)::bigint,
'open',
timestamptz '2026-01-01' + g * interval '30 seconds',
(random() * 100000)::int
FROM generate_series(1, 1000000) AS g;
CREATE INDEX orders_created_idx ON orders (created_at);
ANALYZE orders;
EXPLAIN
SELECT * FROM orders
WHERE created_at >= '2026-01-01' AND created_at < '2026-01-02';
EXPLAIN
SELECT * FROM orders
WHERE date_trunc('day', created_at) = '2026-01-01';The first plan should show a Bitmap Index Scan or Index Scan on orders_created_idx, with an Index Cond containing the two bounds. The second should show a Seq Scan with a Filter containing date_trunc. The first query selects about 2,880 of one million rows, which is narrow enough that the planner prefers the index.
A checklist for slow predicates
Work through the questions in order. Most problems are resolved in the first two.
Exercise
The query SELECT * FROM orders WHERE extract(year FROM created_at) = 2026 AND customer_id = 42; runs against an index on (customer_id, created_at). Rewrite the predicate so both columns can be used for the seek, and say why extract(year FROM created_at) = 2026 blocked the second column.
Show answer
Use WHERE customer_id = 42 AND created_at >= '2026-01-01' AND created_at < '2027-01-01'. The original wrapped created_at in extract, so the index entries, which are sorted by raw created_at, could not be searched by year. Only customer_id narrowed the search, and the year check was applied as a filter to each of that customer's rows. The rewrite leaves created_at bare, so after seeking to customer 42 the database can range-scan just the 2026 entries.
Exercise
A lookup WHERE lower(email) = '[email protected]' is slow, and the table has an ordinary index on email. Why does the existing index not help, and what is the smallest change that fixes it without editing the query?
Show answer
The existing index is sorted by email, not by lower(email), so the planner cannot use it to find lowercase matches. Create an expression index with CREATE INDEX users_lower_email_idx ON users (lower(email));. The query then matches the indexed expression exactly and can descend the tree.