Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Case When statement to count rows on multiple tables

I am trying to write a query which checks whether multiple tables have been populated, so I have to check multiple tables, in case that only one of them has 0 records then I have to return 'No' in output, otherwise if all of those tables have more than 0 (i.e 1,2,3... records) it should return 'YES'.

I have already tried using:

SELECT
    CASE WHEN (SELECT COUNT(*) FROM LorikSkema.TABLE1)  > 0 THEN 'YES'
    ELSE 'NO'
    END FROM DUAL;

This seems to work for only one table, but I'm having trouble finding a suitable query for multiple tables based on this logic.

like image 305
Lorik Berisha Avatar asked Jul 05 '26 15:07

Lorik Berisha


1 Answers

You can use AND to add the checks for the other tables. But I think using EXISTS could be faster than count(*).

SELECT CASE
         WHEN EXISTS (SELECT *
                             FROM table1)
              AND EXISTS (SELECT *
                                 FROM table2)
              ...
              AND EXISTS (SELECT *
                                 FROM tablen) THEN
           'YES'
         ELSE
           'NO'
       END
       FROM dual;
like image 163
sticky bit Avatar answered Jul 07 '26 04:07

sticky bit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!