Suppose I have the following query:
SELECT a.*
FROM a
CROSS JOIN b
GROUP BY a.id -- Primary key
HAVING bool_and(expensive_comparison(a, b))
What will PostgreSQL do with this query? Will it process expensive_comparison
on all pairs, or will it stop and return immediately for a given for a given a.id
?
Is there a more efficient, equivalent way to write this query without resorting to procedural code?
I'm using PostgreSQL 9.3, but if it's changed in any newer versions, that would be relevant info.
Best Answer
It depends on whether the funciton is
IMMUTABLE
or not. All tests done on PostgreSQL 9.5.Now we create sample data.
Now on the
IMMUTABLE
one, noteExecution time: 0.138 ms
,And on the
STABLE
one... noteme not waiting around
And also this exemplifies me not waiting around...
With arguments
Yes, it seems that optimization is lost if you provide arguments