I have a table with a boolean column and want know if atleast one record has a TRUE
value in that column.
This query works as expected with postgresql:
SELECT sum(coalesce(CAST(boolean_column AS INT),0)) <> 0
FROM entity
WHERE correlation_id = 123;
But in case of Microsoft SQL Server i get a syntax error near ‘<‘!
Background is that my application should support both: PostgreSQL and SQL-Server and I don’t want to create different SQL scripts for each database backend.
A work-around may be to use an INT column and handle the boolean expression at application level.
Any hints welcome!
2
Answers
This query solved my problem for both: PostgreSQL and SQL-Server:
Because in PostgreSQL the
boolean_column
is of typeBOOLEAN
and in SQL-Server it is of typeBIT
. PostgreSQL interprets1
asTRUE
and that is all I am interested in (see PostgreSQL - Boolean Type).You can try using EXISTS which is supported by both PostgreSQL and SQL Server, and is generally more performant than a full count of matching rows. The query stops as soon as it finds a single matching row:
SQL Server does not have a TRUE literal and uses 1 for BIT columns, which are typically used to represent boolean values.
In SQL Server, you can modify the query like this:
In PostgreSQL,