Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL view infers nullable column from non-null table?

I have a Product table with non-null "quantity" (decimal) and "status" (int) columns, and I created a view on this table with the following case expression:

SELECT P.ProductTypeId,
       (CASE WHEN P.StatusId IN (5, 8) THEN 0 ELSE -P.Quantity END) AS Quantity,
       ...
FROM Product P

ProductTypeId is correctly inferred as non-null. However, the Quantity column of this view is inferred as nullable, even though the underlying columns are not nullable. This doesn't make any sense to me.

I could use ISNULL/COALESCE to provide a default value in this case and force non-nullability, but there is no meaningful default value, and this shouldn't happen in the first place from what I understand. Any ideas what's going on?

like image 531
naasking Avatar asked May 17 '11 16:05

naasking


1 Answers

The below explanation is for computed columns in a table. I imagine the same applies to computed columns in a view.

The Database Engine automatically determines the nullability of computed columns based on the expressions used. The result of most expressions is considered nullable even if only nonnullable columns are present, because possible underflows or overflows will produce null results as well. Use the COLUMNPROPERTY function with the AllowsNull property to investigate the nullability of any computed column in a table. An expression that is nullable can be turned into a nonnullable one by specifying ISNULL(check_expression, constant), where the constant is a nonnull value substituted for any null result.

An example where your expression could return NULL is

SET ARITHABORT OFF;
SET ANSI_WARNINGS OFF;

WITH Product(Quantity,StatusId) As
(
SELECT -2147483648,1
)
SELECT (CASE WHEN P.StatusId IN (5, 8) THEN 0 ELSE -P.Quantity END) AS Quantity  
FROM Product P
like image 150
Martin Smith Avatar answered Sep 20 '22 13:09

Martin Smith