Marcus Junius Brutus
Marcus Junius Brutus

Reputation: 27306

SELECT EXISTS in Sybase

I have the following query in PostgreSQL (1=1 is a placeholder for some arbitrary condition as apparently I can't write WHERE TRUE in Sybase)

SELECT EXISTS FROM (
    SELECT 1 FROM someTable WHERE 1=1  
)

How do I translate them for SQL Server / Sybase syntax ? A roundabout way is to do:

SELECT COUNT(*) FROM (
    SELECT 1 FROM someTable WHERE 1=1  
) a

… which can further be simplified to:

SELECT COUNT(*) FROM someTable WHERE 1=1  

… but EXISTS is cleaner and I believe it's in the ANSI standard as well.

Upvotes: 4

Views: 8365

Answers (3)

Giorgos Betsos
Giorgos Betsos

Reputation: 72225

Try this:

SELECT IIF(EXISTS (SELECT 1 FROM mytable WHERE 1=1), 1, 0)

Upvotes: 0

SqlZim
SqlZim

Reputation: 38073

exists() doesn't return a value that you can select (I don't know why). You can check if exists(), but not select exists(). You can also check where exists() or even case when exists().

select 
    E = case 
        when exists(
          select 1 from master..spt_values
        ) 
          then 1
        else 0 
        end

If you are trying to get counts for multiple different criteria, a common pattern for sql server would be something like:

select 
    ACount     = sum(case when x='A' then 1 else 0 end)
  , ABCount    = sum(case when x in ('A','B') then 1 else 0 end)
  , TotalCount = count(*) /* or sum(1) */ 
from someTable

Upvotes: 2

Adam Jacobson
Adam Jacobson

Reputation: 564

Not sure what you expect for 'EXISTS' but this might do the trick

SELECT 1 
WHERE EXISTS (SELECT 1 FROM dbo.Table WHERE 1 = 1)

Upvotes: 1

Related Questions