Sub topic 13
Partial and Expression Indexes
Prerequisites and purpose
This chapter assumes you know SELECT, WHERE, primary keys, and basic B-tree indexes. A partial index contains entries for only some rows. An expression index contains the result of an expression, such as lower(email). Both reduce index size and can target a specific workload, but the query must match the index design.
Partial indexes
Suppose an orders table contains many completed orders but your application often searches only open orders:
CREATE INDEX orders_open_created_idx
ON orders (created_at)
WHERE status = 'open';
SELECT id, customer_id, created_at
FROM orders
WHERE status = 'open'
AND created_at >= '2026-01-01'
AND created_at < '2026-02-01';The index stores created_at only for rows whose status is open. The query can use it to find the date range without considering completed rows in this index.
The query planner must be able to prove that the query's filter implies the index predicate. A condition such as status = 'open' matches directly. A condition such as status IN ('open', 'pending') does not guarantee that every matching row belongs to the partial index, so this index may not help.
A partial index is useful when:
- The indexed subset is much smaller than the table.
- Queries repeatedly use the same stable condition.
- The excluded rows rarely need this access path.
Every inserted or updated row whose status changes into or out of the predicate may require index maintenance. A partial index also does not enforce uniqueness across the entire table unless its predicate covers the entire table.
Expression indexes
An expression index stores a calculated value instead of a bare column. This makes normalized searches efficient:
CREATE INDEX users_lower_email_idx
ON users (lower(email));
SELECT id, email
FROM users
WHERE lower(email) = '[email protected]';The expression in the query must match the indexed expression closely enough for the planner to recognize it. An index on lower(email) does not automatically support upper(email) or an arbitrary application-side normalization rule.
Expression indexes are helpful for:
- Case-insensitive lookup.
- Date or numeric transformations used consistently in filters.
- Searches that apply a deterministic normalization step.
The database must recompute the expression when an indexed column changes. The expression also needs to be valid for indexing. In PostgreSQL, functions used in index expressions must be immutable, meaning their result cannot change for the same inputs because of time, configuration, or external state.
Practice
Exercise
An index exists on lower(email). Why might WHERE email = '[email protected]' fail to use it?
Show answer
The query compares the bare email column and does not request the indexed expression. Write WHERE lower(email) = '[email protected]', or create a different index for the desired comparison.