Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL if select statement returns no rows then perform alternative select statement

Tags:

sql

Basically, what syntex would allow me to achieve the title statement?

If (select statement 1) returns 0 rows THEN (select statement 2) else (select statement 3)

So that the sql returns results from either statement 2 or 3 I've looked for a way to do this but nothing I've found so far seems to exactly address the if requirements.

like image 891
YsoL8 Avatar asked Jun 24 '11 10:06

YsoL8


3 Answers

IF EXISTS (SELECT field FROM table)
BEGIN
SELECT field FROM table2
END
ELSE
BEGIN
SELECT field FROM table3
END
like image 86
ChrisBint Avatar answered Nov 16 '22 00:11

ChrisBint


Here you go...

IF ((select count(*) from table1)= 0)
BEGIN
Select * from table2
END
ELSE
BEGIN
SELECT * from table3
END
like image 42
Gans Avatar answered Nov 16 '22 01:11

Gans


Sorry for the lack of feedback. Someone else in the office took an interest and came up with this:

select * from (
        select *
              , (SELECT Count(*) 
                   FROM users 
                  WHERE version_replace = 59 AND moderated = 1) AS Counter 
          FROM users WHERE version_replace = 59 AND moderated in (0,1)
     ) AS y
where Counter = 0 and Moderated = 0
   or Counter > 0 and Moderated = 1
ORDER By ID DESC

Which does what I need.

like image 40
YsoL8 Avatar answered Nov 16 '22 00:11

YsoL8