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.
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