Prince of Sweden Prince of Sweden - 1 year ago 49
SQL Question

SQL - If Select returns nothing then do another Select

I'm currently trying to do an SQL query that can detect if a SELECT query returns nothing, and then do another one if that is the case.

Here is what I mean:

IF SELECT * FROM table WHERE criteria = criteria RETURNS NO ROWS
THEN SELECT * FROM table WHERE criteria2 = criteria2


Is this possible? I don't think that an empty reply counts as "null" so I have a bit of a trouble with that.

Thanks in advance for your help!

Answer Source

You can do this in one statement, assuming the columns are the same:

SELECT *
FROM table
WHERE criteria = criteria 
UNION ALL
SELECT *
FROM table
WHERE criteria2 = criteria2 AND
      NOT EXISTS (SELECT 1 FROM table WHERE criteria = criteria);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download