How can I make SQL Server return a non-nullable bit when using CASE statements?

I’m having trouble with SQL Server and bit columns. I’ve got a table with a smallint column that can be 0, 1, or 2. I made a view that uses a CASE statement to turn this into a bit (1 if the value is 1, 0 otherwise). But when I look at the view in Management Studio, it says the column can be null. This doesn’t make sense to me.

Here’s a simplified version of what I did:

CREATE TABLE MyTable (MyValue smallint NOT NULL)

CREATE VIEW MyView AS
SELECT 
  CASE 
    WHEN MyValue = 1 THEN CAST(1 AS bit)
    ELSE CAST(0 AS bit)
  END AS MyBit
FROM MyTable

Why does SQL Server think MyBit can be null? Is there a way to make it not nullable? I’ve tried wrapping the whole CASE in another CAST but it didn’t help. Any ideas?

I’ve encountered this issue before, and it’s a quirk of SQL Server’s type inference system. Even though your CASE statement doesn’t produce NULL values, SQL Server conservatively assumes it might. Here’s a reliable workaround:

CREATE VIEW MyView AS
SELECT
CASE
WHEN MyValue = 1 THEN 1
ELSE 0
END AS MyBit
FROM MyTable

By removing the CAST and using integer literals, SQL Server correctly infers a non-nullable bit. This approach maintains the desired functionality while ensuring type consistency. If you need to enforce the bit type explicitly, you can add a final CAST outside the CASE statement without affecting nullability.

yo DancingButterfly, i’ve run into this before. SQL Server’s weird with CASE sometimes. Try this trick:

SELECT COALESCE(CASE WHEN MyValue = 1 THEN 1 ELSE 0 END, 0) AS MyBit
FROM MyTable

this forces a non-null bit. lemme know if it works for ya!

hm, interesting problem! have u tried using COALESCE or ISNULL functions? they might help ensure a non-null result. also, what about explicitly setting the column as NOT NULL in the view definition? just brainstorming here. curious to hear if anyone else has encountered this quirk with CASE statements and bit columns?