Short-circuit Postgres query after specific value has been returned

Currently have a query of the form:

SELECT myFunc(col1) FROM myTable;

myFunc returns a bool value. Is it possible to short-circuit query execution so that the query will end the first time myFunc returns a row with the value true? It doesn’t matter the order in which the query is executed, simply that one execution of the function has been found to be true.

EXISTS doesn’t work since it only tests whether or not there are rows returned at all; but myFunc always returns a value (true or false), so EXISTS wouldn’t be helpful in identifying the above stopping condition.

>Solution :

Try this

select mf 
from (SELECT myFunc(col1) as mf FROM myTable) t 
where mf limit 1;

I think that the optimizer will flatten the query and do exactly what you need.

Or using exists as @JasonGoemaat suggests:

select exists 
(
 select from myTable where myFunc(col1)
);

Leave a Reply