Partial Index Predicate Must Be Immutable
Partial index predicates must be IMMUTABLE, so now() inside the WHERE is rejected; gate the index on a stable status column and leave time filters to queries.
Code
-- partial index predicate must be IMMUTABLE: now() is STABLE
CREATE TEMP TABLE incidents (
id bigint PRIMARY KEY,
status text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO incidents VALUES
(1, 'open', now() - interval '1 day'),
(2, 'closed', now() - interval '40 days');
-- 想给“最近 30 天”建 partial index:谓词里的 now() 随时间漂移,直接被拒
-- ERROR: functions in index predicate must be marked IMMUTABLE
-- CREATE INDEX incidents_recent_idx ON incidents (created_at)
-- WHERE created_at > now() - interval '30 days';
-- 现实解法:谓词用稳定字段(status),时间条件留在查询里
CREATE INDEX incidents_open_created_idx
ON incidents (created_at)
WHERE status = 'open';
EXPLAIN (COSTS OFF)
SELECT id
FROM incidents
WHERE status = 'open'
AND created_at > now() - interval '1 day';
-- 对照:CHECK 约束没有易变性限制,stable/volatile 函数可用,写入时逐行检查
ALTER TABLE incidents
ADD CONSTRAINT incidents_created_not_future
CHECK (created_at < now() + interval '1 hour');Why now() cannot live in the predicate
A partial index’s WHERE is evaluated once at build time and must hold identically for every future row, so PostgreSQL requires its functions to be IMMUTABLE. now() is STABLE — it changes per transaction — so the commented-out index … WHERE created_at > now() - interval '30 days' is rejected with the file’s quoted error message (functions in index predicate must be marked IMMUTABLE). The working alternative gates the index on the stable column status = 'open' and leaves the time comparison to the query, where it is evaluated per execution.
What the plan shows
Index Scan using incidents_open_created_idx on incidents
Index Cond: (created_at > (now() - '1 day'::interval))
The EXPLAIN (COSTS OFF) output (node naming varies slightly by version) shows the planner matching the query’s status = 'open' term against the index predicate, with the time filter applied as an index condition on the indexed created_at column — the partial index serves the query even though its predicate mentions no time at all.
The contrast at the end of the file
ALTER TABLE incidents
ADD CONSTRAINT incidents_created_not_future
CHECK (created_at < now() + interval '1 hour');
A CHECK constraint has no immutability restriction — it is evaluated per row at write time, so STABLE and VOLATILE functions are fine there, unlike in index predicates.
Interactive Tools for This Topic
FAQ
- Which tables appear in this script?
- `incidents`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.