4

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.

Marcus Junius Brutus
  • 26,087
  • 41
  • 189
  • 331

3 Answers3

2

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
SqlZim
  • 37,248
  • 6
  • 41
  • 59
1

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)
Adam Jacobson
  • 564
  • 4
  • 9
0

Try this:

SELECT IIF(EXISTS (SELECT 1 FROM mytable WHERE 1=1), 1, 0)
Giorgos Betsos
  • 71,379
  • 9
  • 63
  • 98