I have a table of the following form:
[mytable]
id, min, max, funobj
-----------------------------------------
1 15 23 {some big object}
1 23 41 {another big object}
1 19 27 {next big object}
Now suppose I have a view created like this:
CREATE VIEW functionvalues AS
SELECT id, evaluate(funobj)
FROM mytable
where evaluate is a set-returning function evaluateing the large funobj. The result of the view could be something like this:
id, evaluate
--------------
1 15
1 16
1 ...
1 23
2 23
2 24
2 ...
2 41
...
I do not have any information on the specific values evaluate will return, but I know that they will alway be between the min- and max-values given in mytable
(including boundaries)
Finally, I (or better, a third party application) makes a query on the view:
SELECT * FROM functionvalues
WHERE evaluate BETWEEN somevalue AND anothervalue
In this case, Postgres does evaluate the function evaluate for every row in mytable, whereas, depending on the where clause, the function does not have to be evaluated if it's max and min are not between the given values. As evaluate is a rather slow function, this gives me a very bad performance.
The better way would be to query the table directly by using
SELECT *
FROM (
SELECT id, evaluate(funobj)
FROM mytable
WHERE
max BETWEEN somevalue AND anothervalue
OR min BETWEEN somevalue AND anothervalue
OR (min < somevalue AND max > anothervalue)
) AS innerquery
WHERE evaluate BETWEEN somevalue AND anothervalue
Is there any way I can tell postgres to use a query like the above (by clever indices or something like that) without changing the way the third party application queries the view?
P.S.: Feel free to suggest a better title to this question, the one I gave is rather... well... unspecific.