Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading