I want to return 1 if some number already exists in table and 0 otherwise.
I tried something but it doesn't work:
select
case when 100 in (select distinct id from test) then '1'
else '0'
from test
I want something similar to exists function that already exists in PostgreSQL, but instead of true and false I want 1 or 0.
EXISTSyields abooleanresult.The simple way to achieve what you are asking for is to cast the result to
integer:TRUEbecomes1.FALSEbecomes0.See:
Or with
UNION ALL/LIMIT 1(probably slightly faster):If a row is found,
1is returned and Postgres stops execution due toLIMIT 1. Else,0is returned.Disclaimer for the
UNION ALLsolution: this relies on undocumented behavior that Postgres would executeUNION ALLterms in sequence. This used to be the case until Postgres 11, whereParallel Appendwas added to Postgres. It's actually still the case (currently Postgres 15) for the given example, as retrieving a single row will never trigger aParallel Appendplan. But it remains undocumented behavior, so you might not want to rely on it. See: