1

I have two queries, query1 and query2. What I would like to do is, if returned rows of query1 is empty, return query2 instead. Is that possible using basic SQL query alone? They have same returning columns btw, but different table sources.

eg:

query1:

SELECT name, message
FROM table1

query2:

SELECT name, message
FROM table 2

If query1 is empty, return name, message from query2.

superigno
  • 994
  • 2
  • 12
  • 24
  • @supergino can you explain what you want to do in a little more detail. I am reading if there is one row in table1 and 100 in table 2 you only want the 1 row from table1. Only when table1 is empty do you want to select from table2 – EoinS May 30 '16 at 04:44

2 Answers2

3

This will select from table1 if not empty, otherwise select from table2:

SELECT * FROM table1
WHERE EXISTS (select * from table1) 
UNION ALL
SELECT * FROM table2
WHERE NOT EXISTS (select * from table1)

This checks if table1 has no rows:

EXISTS (SELECT * FROM TABLE) 
EoinS
  • 5,405
  • 1
  • 19
  • 32
0

Found an answer here: https://stackoverflow.com/a/25122516/3747493

Basically:

SELECT *
  FROM table1
UNION ALL
SELECT *
  FROM table2
WHERE (SELECT COUNT(*) FROM table1) = 0

Thanks guys!

Community
  • 1
  • 1
superigno
  • 994
  • 2
  • 12
  • 24