You cannot use aggregate functions or subquery expressions in a partial index predicate . In any case, this would hardly make sense, given the nature of the IMMUTABLE indexes.
If you have a number of integers and you can guarantee that the maximum will always be greater than x , you can use this meta-information.
CREATE INDEX text_max_idx ON test (a) WHERE a > x;
This index will only be used by the query planner if you include a WHERE that matches the index predicate. For instance:
SELECT max(a) FROM test WHERE a > x;
There may be more conditions, but this one must be included to use the index.
I take warranty seriously. Your query will not return anything if the predicate is false.
You can create fault tolerance:
SELECT COALESCE( (SELECT max(a) FROM test WHERE a > x) (SELECT max(a) FROM test));
You can generalize this approach with more than one partial index. Like this technique , much simpler.
I would consider a trigger approach, though, with the exception of very large write loads in the table.
source share