Sub topic 13
Partial and Expression Indexes
This chapter assumes you can read basic EXPLAIN output, know how a B-tree index serves point lookups and range scans, and understand why predicates must leave the indexed column bare. The examples use PostgreSQL syntax. Both features also exist in SQLite. MySQL 8.0 supports expression indexes (called functional key parts) but not partial indexes. SQL Server has filtered indexes, which work like partial indexes.
Why a plain index is sometimes the wrong shape
A plain B-tree index stores one entry for every row in the table, keyed on the raw column value. That fits many queries, but two common situations fit it badly.
- The queries only ever touch a small, well-defined slice of the table. Examples are open orders, unprocessed jobs, and non-deleted users. A full index spends space and write effort on millions of rows that no query asks about.
- The queries compare a computed value, such as
lower(email), rather than the stored value. The raw column's index is useless for these, because the planner cannot search byemailwhen the predicate is onlower(email).
Partial indexes address the first situation. Expression indexes address the second. They can be combined.
Partial indexes
A partial index has a WHERE clause. Only rows that satisfy it get index entries.
CREATE INDEX orders_open_created_idx
ON orders (created_at) WHERE status = 'open';Suppose orders holds 50 million rows and 40,000 of them have status = 'open'. The index above holds 40,000 entries. A full index on created_at would hold 50 million. The partial version is smaller, so it caches better, scans faster, and costs less to maintain.
Write savings
An insert whose row does not match the predicate does not touch the index at all. An update that changes a row from 'open' to 'shipped' removes the entry. An update that does not touch the indexed columns or the predicate columns usually adds no index work. In a table where most rows are in a terminal state, this removes most of the index's write overhead.
When the planner can use it
The planner uses a partial index only if it can prove that the query's WHERE clause implies the index predicate. The proof is fairly literal.
-- Can use orders_open_created_idx: the query repeats the predicate.
SELECT id, created_at
FROM orders
WHERE status = 'open' AND created_at >= now() - interval '1 day';
-- Cannot use it: nothing says status = 'open'.
SELECT id, created_at
FROM orders
WHERE created_at >= now() - interval '1 day';The second query might match rows outside the index, so using the index would return wrong results. The planner therefore rejects it.
The implication check handles simple cases, such as a query on x > 10 against an index predicate of x > 5. It does not reason broadly. If your query uses a different form of the condition, for example status IN ('open') against an index on status = 'open', test it with EXPLAIN.
Parameters and prepared statements
The proof happens at plan time. If a query passes the status as a parameter (WHERE status = $1), a generic prepared-statement plan cannot assume $1 = 'open', so it cannot use the partial index. Custom plans, which are built with the actual value, can. If a partial index is ignored from application code but used in psql, check this first. The simplest fix is to write the constant into the query text.
Common uses
- Queue and status tables. Index only unprocessed work:
CREATE INDEX jobs_pending_idx ON jobs (run_at) WHERE done_at IS NULL;. The index stays small no matter how many finished jobs pile up. - Soft deletes. Index only live rows with
WHERE deleted_at IS NULL. - Skewed values. When one value dominates the column, index everything except that value. This pairs with the selectivity rule from earlier: an index on a value that matches most of the table would not be used for it anyway.
- Conditional uniqueness. A unique partial index enforces a constraint on a subset of rows.
-- Each user may have at most one active subscription,
-- but any number of cancelled ones.
CREATE UNIQUE INDEX subscriptions_one_active_idx
ON subscriptions (user_id) WHERE status = 'active';This is often the cleanest way to express a rule such as "unique among non-deleted rows". A plain unique constraint cannot express it.
Expression indexes
An expression index stores the result of an expression computed from the row, rather than a column value.
CREATE INDEX users_lower_email_idx ON users (lower(email));
SELECT * FROM users WHERE lower(email) = '[email protected]';The index is a B-tree keyed on lower(email). The planner matches it when the query contains the same expression. In the query above, the left side is exactly the indexed expression, so the plan can use an index scan.
This is the usual remedy for the non-sargable pattern from the previous chapter. Wrapping a column in a function stops a plain index from working. Indexing the function's result makes the wrapped form searchable.
-- Not index-friendly on a plain index over created_at:
SELECT count(*) FROM orders
WHERE date_trunc('month', created_at) = '2026-01-01';You have two fixes. You can rewrite the query as a bare range on created_at, which is usually better because it reuses the plain index. Or you can create an expression index on date_trunc('month', created_at) when you cannot change the query, such as when it comes from a reporting tool.
Rules for expression indexes
- The expression must be immutable. It must return the same output for the same input, always. PostgreSQL rejects functions marked
STABLEorVOLATILE. For example,now()is not allowed, and neither is a conversion that depends on the session time zone. Castingtimestamptztodatedepends on theTimeZonesetting, so it is rejected.(created_at AT TIME ZONE 'UTC')::dateis immutable and accepted. - The query must repeat the expression.
lower(email)andemail ILIKE '[email protected]'are different expressions to the planner. Matching is structural, so keep the form identical, including casts. - Extra parentheses are required in some forms. A bare function call is fine, as in
(lower(email)). For an operator expression, the whole thing must be wrapped:ON orders ((total_cents / 100)). - Maintenance cost is per write. The expression is evaluated on every insert, and on every update that could change its inputs. An expensive function slows writes.
- Changing the function breaks the index. If you redefine an immutable function that an index depends on, the stored entries no longer match its output. Rebuild with
REINDEXafter any such change.
Expression indexes and collation
lower(email) handles case-insensitive matching for ASCII text. For other languages, the result depends on locale and collation rules. Alternatively, PostgreSQL's citext type or a case-insensitive collation can make the column itself case-insensitive, which removes the need for the expression. Choose one approach per column and use it consistently.
Statistics
For a plain column, the planner has per-column statistics to estimate how many rows match. For an expression index, PostgreSQL collects statistics on the expression's values when the table is analyzed. Until ANALYZE has run after creating the index, row estimates may be poor. Run ANALYZE orders; after creating an expression index on a table with data.
Combining the two
Nothing prevents using both features together. This index covers only live users and keys on the lowercase email.
CREATE UNIQUE INDEX users_live_email_idx
ON users (lower(email)) WHERE deleted_at IS NULL;A query uses it only if it contains lower(email) = ... and deleted_at IS NULL. It also enforces that no two live users share an email address ignoring case, while deleted accounts do not block reuse.
Checking that the index is used
Always confirm with EXPLAIN. Check three things in the plan: that the node is an Index Scan, Index Only Scan, or Bitmap Index Scan on your index's name; that the estimated row count is close to what you expect; and that the filter appears as an Index Cond rather than a separate Filter line.
EXPLAIN
SELECT id FROM orders
WHERE status = 'open' AND created_at >= now() - interval '1 day';If you see a Seq Scan, the likely causes are a predicate that does not imply the index condition, an expression that differs from the indexed one, stale statistics, or a result set so large that scanning is cheaper.
Trade-offs and when to avoid them
| Feature | Benefit | Cost or limit |
|---|---|---|
| Partial index | Smaller, cheaper to write, enables conditional uniqueness | Serves only queries that imply the predicate; bind parameters can defeat it |
| Expression index | Makes computed comparisons searchable | Must be immutable; query must repeat the exact expression; computed on every write |
Both add to the number of indexes the table must maintain. Create them for a specific, measured query, not speculatively. A partial index whose predicate drifts away from what the application queries becomes dead weight. Document the intent in a comment on the index, and recheck when the status values or query code change.
flowchart TDExercise
A table tickets has 20 million rows. About 5,000 have state = 'open'. A dashboard runs SELECT id FROM tickets WHERE state = 'open' ORDER BY created_at LIMIT 50 every second. Write an index suited to this query, and explain why a plain index on (state, created_at) is a worse choice here.
Show answer
CREATE INDEX tickets_open_created_idx ON tickets (created_at) WHERE state = 'open';. The index holds about 5,000 entries and returns rows already in created_at order, so the LIMIT 50 can stop early. The plain (state, created_at) index would hold 20 million entries, take more memory and cache, and add write work for every ticket in every state, though it would also serve the query correctly.
Exercise
You created CREATE INDEX ON users (lower(email)). Which of these queries can use it, and why? (a) WHERE lower(email) = '[email protected]' (b) WHERE email = '[email protected]' (c) WHERE upper(email) = '[email protected]'
Show answer
Only (a). The planner matches the exact indexed expression lower(email). Query (b) uses the raw column, and (c) uses a different function, so neither matches the index's key.