Sub topic 10
Why Index Expressions Must Be Immutable
Assume you know basic SELECT, WHERE, ORDER BY, and CREATE INDEX. This chapter also assumes that you can read a simple EXPLAIN plan. The examples use PostgreSQL and the orders table from earlier chapters.
What immutability means
An immutable function always returns the same result when given the same inputs. For example, lower(text) is immutable:
SELECT lower('[email protected]');The result does not depend on the current time, session settings, database contents, or another external value.
PostgreSQL stores the result of an index expression in the index. When a row is inserted or updated, PostgreSQL evaluates the expression and stores its value. Later, a query can search that stored value without calculating the expression for every row.
flowchart TD
A[Insert or update a row] --> B[Evaluate the index expression]
B --> C[Store the computed value in the index]
D[Query uses the same expression] --> E[Search stored index values]
C --> Ecaption: How PostgreSQL uses an expression index alt: A flow from row changes through expression evaluation and stored index values to a query search.
If the expression could produce a different result later, the stored index value could become wrong. PostgreSQL therefore requires every function and operator used by an index expression to be immutable.
Function volatility categories
PostgreSQL classifies functions by how consistently they return results.
| Category | Meaning | Allowed in an index expression |
|---|---|---|
| `IMMUTABLE` | Same inputs always produce the same result | Yes |
| `STABLE` | Same result during one statement, but may depend on settings or database state | No |
| `VOLATILE` | May change each call | No |
A function that reads the current time is volatile. A function that depends on the session time zone can be stable or otherwise unsuitable for an index, even if its explicit argument is unchanged.
Time zones can make an expression unsafe
Consider a timestamptz column. Casting it to date uses the session's TimeZone setting. The same timestamp can therefore become different dates in different sessions.
-- This is rejected because the cast depends on the session time zone.
-- CREATE INDEX orders_created_date_bad
-- ON orders ((created_at::date));
-- This fixes the time zone as part of the expression.
CREATE INDEX orders_created_date_utc_idx
ON orders (((created_at AT TIME ZONE 'UTC')::date));
EXPLAIN
SELECT count(*)
FROM orders
WHERE (created_at AT TIME ZONE 'UTC')::date = DATE '2026-01-15';The query must use the same expression, including the chosen time zone. An index on the UTC date does not directly match a query that uses the local session date.
Partial-index predicates
A partial index has a predicate, which is the condition deciding which rows enter the index. That predicate must also be based on immutable behavior.
CREATE INDEX orders_pending_created_idx
ON orders (created_at)
WHERE status = 'pending';The equality comparison between fixed text values is safe. A predicate such as created_at > now() - interval '1 day' is not allowed. Its membership would change as time passes, but PostgreSQL does not continuously rebuild the index when now() changes.
The query can contain changing values. The restriction applies to the index definition, not every query condition:
SELECT id, created_at
FROM orders
WHERE status = 'pending'
AND created_at < now() - interval '1 hour';The partial index can help with this query because the query's conditions include the indexed subset.
Practical design rule
Before creating an expression or partial index:
- Check whether every function and operator is immutable.
- Make environment-dependent settings explicit, such as
UTC. - Repeat the indexed expression exactly in the query.
- Use
EXPLAINto confirm that the planner can use the index.
Exercise
Why is created_at::date unsafe for an index on a timestamptz column, and how can you make it safe?
Show answer
The cast depends on the session time zone, so the same value can produce different dates. Apply a fixed zone first, such as (created_at AT TIME ZONE 'UTC')::date.