HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Select where bit is not 0

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
selectwherebitnot

Problem

I have made the following query to select a record that isn't 0.

SELECT * FROM Table WHERE Bit != 1 OR Bit IS NULL;


Why is the check Bit != 1 not enough for a nullable BIT?

Solution

See following results:

  • 'true' != 'true' → false



  • 'false' != 'true' → true



  • NULL != 'true' → null (and equivalent to false in WHERE because it is not true)



What you can do is use COALESCE to change null into 'false'

SELECT * FROM Table WHERE COALESCE(Bool, 'false') != 'true';

Code Snippets

SELECT * FROM Table WHERE COALESCE(Bool, 'false') != 'true';

Context

StackExchange Database Administrators Q#102720, answer score: 3

Revisions (0)

No revisions yet.