3

Table format:

+---------+---------+-----------------+
| column1 | column2 | column3| column4| 
+---------+---------+-----------------+
| value1  | true    | true   | false  |
| value2  | true    | false  | true   |
| value4  | false   | false  | false  |
+---------+---------+-----------------+

Column 1 to 4 has data type Boolean.

I want to check whether all these Boolean column values are false or at least one column value is true.

Is there any better way to do this using a SQL Server query? Expected output:

+---------+---------+-----------------+
| column1 | column2 | column3| column4| 
+---------+---------+-----------------+
| value1  | true    | true   | false  | = true
| value2  | true    | false  | true   | = true
| value4  | false   | false  | false  | = false
+---------+---------+-----------------+

3 Answers3

8

Just use bitwise operators if bit data type.

DECLARE @foo table (column1 bit, column2 bit, column3 bit, column4 bit)
INSERT @foo VALUES (1, 1, 0, 1), (0, 1, 0, 0), (0, 0, 0, 0)

SELECT
    CASE
        WHEN column1 | column2 | column3 | column4 = 0 THEN 'All false'
        ELSE 'Some true' 
    END
FROM @foo;

Very simple, no CASTs involved

gbn
  • 422,506
  • 82
  • 585
  • 676
1

In SQL Server, there's no boolean type, but there's a bit datatype, which I use instead, it's basically 0 and 1 (obviously). So your table would become table of zeros and ones, 0 - false, 1 - true. So to check if at least one column is true out of four, simply add all values and check if it's greater than zero (if all are false, then the sum wuold be equal to zero), like:

case when cast(column1 as int) + 
          cast(column2 as int) + 
          cast(column3 as int) + 
          cast(column4 as int) > 0 then 'at least one true' else 'all false' end
Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
  • You'll get an error, "The data types bit and bit are incompatible in the add operator." – gbn Mar 26 '18 at 07:02
0

SQL Server doesn't have Boolean type, it has BIT type to represent boolean data

select a.column1, 
      case when sum(a.value) >= 1 
           then 'one or more is true' else 'all is false' end [CheckBoolVal]
from table t cross apply (
        values (column1, col2), (column1, col3), (column1, col4) )a(column1, value)
group by a.column1

Result :

column1 CheckBoolVal
value1  one or more is true
value2  one or more is true
value4  all is false
Yogesh Sharma
  • 49,870
  • 5
  • 26
  • 52