Expression Index Needs Immutable Functions

Create expression indexes only from IMMUTABLE functions: upper() qualifies, while STABLE helpers like age(timestamp) are rejected outright.

SqlData Fetching

Code

snippet
-- 表达式索引只接受 IMMUTABLE 函数:upper() 是,能建
CREATE INDEX readings_station_upper_idx ON readings (upper(station_code));

SELECT id FROM readings WHERE upper(station_code) = 'NOR-04';

-- age(timestamp) 单参版依赖"今天",是 STABLE:
-- 放进索引表达式会被直接拒绝
-- CREATE INDEX crew_tenure_idx ON crew (age(birth_date));

-- 查询表达式没有这个限制:STABLE 函数随便用
SELECT id, age(birth_date, current_date) AS tenure FROM crew;

-- 判定函数的易变性类别:查 pg_proc 就能确认,不用猜
SELECT
    proname,
    provolatile   -- i=IMMUTABLE / s=STABLE / v=VOLATILE
FROM pg_proc
WHERE proname IN ('upper', 'age', 'clock_timestamp');

What the code does

SELECT / CREATE statements share the script, touching readings, crew and pg_proc.

Breaking the statements into their working parts: a WHERE clause constraining which rows the statement operates on.

Applying it

Run the statement against the readings table.

Statements that matter

SELECT
    proname,
    provolatile   -- i=IMMUTABLE / s=STABLE / v=VOLATILE
FROM pg_proc
WHERE proname IN ('upper', 'age', 'clock_timestamp');
SELECT id FROM readings WHERE upper(station_code) = 'NOR-04';
CREATE INDEX readings_station_upper_idx ON readings (upper(station_code));

Interactive Tools for This Topic

FAQ

What objects does the SQL involve?
`readings`, `crew`, `pg_proc`.