Skip to content
Advertisement

Return 1 if number exists in table and 0 otherwise

I want to return 1 if some number already exists in table and 0 otherwise.

I tried something but it doesn’t work:

I want something similar to exists function that already exists in PostgreSQL, but instead of true and false I want 1 or 0.

Advertisement

Answer

EXISTS yields a boolean result.
The simple way to achieve what you are asking for is to cast the result to integer:

TRUE is 1.
FALSE is 0.

Or with UNION ALL / LIMIT 1 (probably slightly faster):

If a row is found, 1 is returned and Postgres stops execution due to LIMIT 1.
Else, 0 is returned.

See:

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement