Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL IF SELECT query is null then do another query

I have a query that regularly returns "nothing", and I would like to run a different query if this is the case, but I know not of the way of doing this. If anyone could be of help please.

Here is the current code I am using...

SELECT * FROM cfg_users JOIN cfg_ash ON cfg_users.iUserId = cfg_ash.iUserid WHERE iTeamId='0' AND sDisabled IS NULL AND iStatusId > 0 AND sDate = '2014-08-01' GROUP BY cfg_users.iUserId ORDER BY iStatusId, sName

I basically want to say

IF <my code> IS NULL THEN <do other code>, IF <my code> IS NOT NULL THEN return the result.

Thanks

like image 410
Greylegface Avatar asked Aug 04 '14 14:08

Greylegface


People also ask

How do you execute a 2nd query if the first one returns nothing?

If both queries can only return a single row (or nothing), there is a simple, efficient solution without CTEs: ( SELECT column1, column2 FROM mytable WHERE <1st SET OF complex conditions> ) UNION ALL ( SELECT column1, column2 FROM mytable WHERE <2nd SET OF complex conditions> ) LIMIT 1; Related: Save this answer.

How do you execute a SQL query only if another SQL query has no results?

The common table expression ( WITH clause) wraps the first query that we want to execute no matter what. We then select from the first query, and use UNION ALL to combine the result with the result of the second query, which we're executing only if the first query didn't yield any results (through NOT EXISTS ).

How do you do if then else in SQL?

Any T-SQL statement can be executed conditionally using IF… ELSE. If the condition evaluates to True, then T-SQL statements followed by IF condition in SQL server will be executed. If the condition evaluates to False, then T-SQL statements followed by ELSE keyword will be executed.

Can I join two select statements?

To combine two or more SELECT statements to form a single result table, use the set operators: UNION, EXCEPT or INTERSECT.


1 Answers

There are some simple way only use sql.

Define your first query as a temp table, with union all, filter the second query with temp table's count.

with temp as (select * from t1 where 1=0)
select * from temp
union all
select * from t2 where (select count(*) from  temp) =0

This query will return the second table's records.

with temp as (select * from t1 )
select * from temp
union all
select * from t2 where (select count(*) from  temp) =0

And if temp query have result, only return temp query.

You can test with sql fiddle here.

like image 157
jan Avatar answered Sep 28 '22 03:09

jan