Instead of looking for something in the DBI, you can use SQL to do this. Just wrap SELECT in another SELECT clause with an EXISTS clause:
SELECT 1 FROM DUAL WHERE EXISTS ( SELECT ... );
This is not portable SQL: FROM DUAL may look different on your RDBMS, your database may not support EXISTS and subqueries. However, most modern databases allow you to cook something like this.
This should be the most efficient way, because the optimizer may skip ignoring the order by groups, restrictions on an additional request. Check execution plans.
SELECT COUNT(*) FROM ( SELECT ... )
It is also possible, but the DB must check the entire data set to get the correct number of rows.
If you control the SQL constructor, you can reverse the order, group by (only if you donโt have a part), and apply a limit on top to select only one row.
source share