0

Is it possible to write a SQL query that does the following:

Select * From Table1 

if there are results, return them. Otherwise, use an alternative query and return it's results:

Select * From Table2

I came ups with the following, but it does not seem to work:

IF EXISTS(select * From TableA)
begin
 Select * from TableA 
end
else
 Select * from TableB

Is there a simple elegant way of accomplishing this?

1
  • You can only do this in a single query if both tables have the same columns. Commented Mar 19, 2018 at 14:35

2 Answers 2

3

You can do a UNION query with NOT EXISTS:

SELECT * FROM TABLE1
UNION ALL
SELECT * FROM TABLE2 WHERE NOT EXISTS (SELECT * FROM TABLE1)

*Assuming the columns and types are the same

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the reply, just to clarify if the initial Select returns results the second Select will never fire because the NOT EXISTS will be false. Is that correct?
@Mutuelinvestor That is correct. Or... more technically the second query will fire because it is all one query, but it will return 0 records because the NOT EXISTS.
0

If both tables have same number of columns and the column names are same then you use Union, like below.

Select * from TableA
Union
Select * from TableB

If they have different column names or different number of columns then you can use below code.

Select Col_1 as col1, col_2 as col2.... From TableA
Union
Select col_a as Col1, col_b as Col2..... From TableB

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.