Sub topic 10
Why index expressions must be immutable
This chapter assumes you can read basic CREATE INDEX syntax and have seen an expression index such as lower(email). It uses the orders and users tables from earlier chapters. You will learn what "immutable" means for a function, why PostgreSQL enforces it for index expressions, and how to fix the errors it produces.
What an expression index stores
An expression index does not compute its value when you query. PostgreSQL evaluates the expression once for each row when the row is inserted or updated, and it stores the result in the B-tree. A query such as WHERE lower(email) = '[email protected]' then searches those stored values.
This only works if the stored value stays correct. If lower(email) produced '[email protected]' at insert time and a different answer a day later for the same input, a lookup would walk the tree to the wrong place. It could miss rows that match or return rows that do not. The index would be silently corrupt.
PostgreSQL prevents this by requiring that every function in an index expression always returns the same result for the same arguments. That property is called immutability.
Function volatility categories
Every PostgreSQL function carries a volatility label. The label is a promise the function author makes to the planner.
| Label | Promise | Examples |
|---|---|---|
| `IMMUTABLE` | Same arguments always give the same result, regardless of database state or settings. | `lower(text)`, `abs(integer)`, `length(text)` |
| `STABLE` | Same arguments give the same result within a single statement, but the result may change between statements. | `now()`, `current_setting()`, `to_char(timestamptz, text)` |
| `VOLATILE` | The result may change at any time, even within one statement. | `random()`, `nextval()`, `clock_timestamp()` |
Only IMMUTABLE functions are allowed in index expressions. You can look up the label in the system catalog. In pg_proc, provolatile is i for immutable, s for stable, and v for volatile.
SELECT proname, provolatile
FROM pg_proc
WHERE proname IN ('lower', 'now', 'random')
ORDER BY proname;The query returns i for lower, s for now, and v for random.
The time zone trap
The most common way to hit this rule is a cast from timestamptz to date. A timestamptz value is a moment in time. Turning it into a calendar date requires a time zone, and the cast uses the session's TimeZone setting. The same created_at value is January 15 in one session and January 16 in another. The cast is therefore STABLE, not IMMUTABLE.
CREATE INDEX orders_created_date_bad ON orders ((created_at::date));PostgreSQL rejects this statement:
ERROR: functions in index expression must be marked IMMUTABLEIf PostgreSQL allowed it, rows indexed under one session's time zone would be filed under dates that another session's time zone disagrees with. The fix is to remove the dependence on the session by naming the zone in 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';Two things make this work:
created_at AT TIME ZONE 'UTC'with a literal zone name is immutable. It converts thetimestamptzinto atimestamp(without time zone) using a fixed zone.- Casting a
timestamptodateinvolves no zone at all, so that cast is immutable.
The double parentheses around the whole expression are required syntax. An index element that is more than a plain function call must be wrapped in its own parentheses.
The query must repeat the same expression. If you write WHERE created_at::date = ... instead, the planner does not match it to orders_created_date_utc_idx, because the expression text differs.
Passing a zone name that comes from a column or a setting would break the guarantee, so a non-constant zone is not allowed either.
Partial index predicates follow the same rule
The immutability requirement also applies to the WHERE clause of a partial index. The predicate decides which rows belong in the index. If it could change its answer for a row over time, rows would need to enter and leave the index with no write to trigger the change.
This is the classic mistake:
CREATE INDEX orders_recent_idx
ON orders (created_at)
WHERE created_at > now() - interval '7 days';ERROR: functions in index predicate must be marked IMMUTABLEnow() is stable, and a row that is "recent" today is not recent next week. The index cannot move rows out on its own. Use a predicate based on the row's own data instead, such as status = 'pending', which only changes when the row is updated. Then put the time filter in the query, where now() is allowed:
CREATE INDEX orders_pending_created_idx
ON orders (created_at)
WHERE status = 'pending';
SELECT id
FROM orders
WHERE status = 'pending'
AND created_at < now() - interval '1 hour';The index holds all pending orders. The query narrows them by time at run time.
How the check works
PostgreSQL checks volatility when you run CREATE INDEX, using the labels in the catalog, not by analyzing what the function really does. The decision looks like this:
Because the check trusts labels, a function that is labeled wrongly passes. That is the danger described next.
Writing your own immutable function
You can wrap logic in a function and index the call. This is useful when the same normalization appears in many queries and you want one definition.
CREATE FUNCTION normalize_email(text) RETURNS text
LANGUAGE sql IMMUTABLE
AS $$ SELECT lower(btrim($1)) $$;
CREATE INDEX users_normalized_email_idx
ON users (normalize_email(email));
EXPLAIN
SELECT id FROM users WHERE normalize_email(email) = '[email protected]';This is honest labeling, because lower and btrim are both immutable. Queries must call normalize_email(email), not the inner expression, because the index is matched against the expression as the query states it.
Mislabeling is the failure mode to avoid. Suppose you wrap the time-zone-dependent cast and claim it is immutable:
CREATE FUNCTION created_date(timestamptz) RETURNS date
LANGUAGE plpgsql IMMUTABLE
AS $$ BEGIN RETURN $1::date; END $$;
CREATE INDEX orders_created_date_wrong_idx ON orders (created_date(created_at));PostgreSQL accepts this, because the label says IMMUTABLE. But the function still depends on the session's TimeZone. Rows inserted by sessions with different settings are stored under different dates, and lookups return wrong results with no error. Never label a function IMMUTABLE unless its output depends only on its arguments.
Hidden dependencies to watch for
Some functions look pure but depend on something outside their arguments:
- Session settings.
TimeZone,DateStyle, andsearch_pathchange the output of many date and text conversions. This is whyto_char(timestamptz, ...)and casts between text and dates are not immutable. - Current time and sequences.
now(),current_date, andnextval()are never immutable. - Other tables. A function that runs a
SELECTagainst another table can return different results as that table changes. Do not mark such a functionIMMUTABLE. - Collation. Text functions such as
lower()are immutable, and they use the column's collation. If the operating system or ICU library changes its collation rules, stored index values can become inconsistent with new comparisons. After such a change, rebuild affected indexes withREINDEX.
Quick diagnosis checklist
When CREATE INDEX fails with an immutability error, work through these steps:
- Find which function in the expression is not immutable, using the
pg_procquery above. - If the cause is a time zone, fix the zone with
AT TIME ZONE 'UTC'(or the zone you need) on a literal. - If the cause is
now()or similar in a partial index predicate, move the time condition into the query. - If the logic is yours, check that it uses only its arguments and other immutable functions before you add the
IMMUTABLElabel. - After creating the index, run
EXPLAINwith the exact expression to confirm the planner matches it.
Exercise
A teammate writes CREATE INDEX orders_today_idx ON orders (id) WHERE created_at::date = current_date; and gets an immutability error. Give two reasons it fails, and describe a design that supports "orders from today" lookups.
Show answer
There are two problems. current_date is stable: it changes every day, so rows would have to leave and enter the index without being written. created_at::date on a timestamptz column is also not immutable, because it depends on the session TimeZone. A working design is a plain index on created_at, or an expression index on (created_at AT TIME ZONE 'UTC')::date. The query then supplies the date, for example WHERE (created_at AT TIME ZONE 'UTC')::date = (now() AT TIME ZONE 'UTC')::date, or a range on created_at that uses the plain index.
Exercise
You create users_lower_email_idx on lower(email). A query uses WHERE email ILIKE '[email protected]'. Will the planner use the index, and what query form guarantees a match?
Show answer
No. The planner matches index expressions to the expressions written in the query, and ILIKE on email does not contain lower(email). Write WHERE lower(email) = '[email protected]'. The expression must be the same as the one in the index definition.