21

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.

3
  • 1
    strange objective. what is the physical sense of it?
    – heximal
    Jun 24, 2011 at 10:08
  • which RDBMS? do you want to do this in pure sql, or as part of a script?
    – davek
    Jun 24, 2011 at 10:14
  • Do you mean "if no rows from 1st select, use a 2nd select", rather than usign 3 tables?? And are all result sets the same shape (You wouldn't change the resultset dynamically because the contract then changes.)
    – gbn
    Jun 24, 2011 at 10:23

3 Answers 3

37
IF EXISTS (SELECT field FROM table)
BEGIN
SELECT field FROM table2
END
ELSE
BEGIN
SELECT field FROM table3
END
2

Here you go...

IF ((select count(*) from table1)= 0)
BEGIN
Select * from table2
END
ELSE
BEGIN
SELECT * from table3
END
2
  • 3
    Most optimizers are smart enough to finish evaluating an EXISTS clause as soon as one matching row has occurred. Some optimizers are too dumb to realize that you're planning to compare a COUNT(*) against 0, and will evaluate all rows to compute the count. Jun 24, 2011 at 10:21
  • Agreed...if 0 is all we want to compare with; EXISTS is all that makes sense! Other cases count might help.
    – Gans
    Jun 24, 2011 at 10:25
1

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.

0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.