Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using nullable columns in a WHERE clause

Assume a table definition in SQL Server as follows:

CREATE TABLE MyTable (
  Id   UNIQUEIDENTIFIER NULL,
  Info VARCHAR(MAX)
)

And a query:

DECLARE @id UNIQUEIDENTIFIER
DECLARE @info VARCHAR(MAX)
IF @id IS NOT NULL
BEGIN
  SELECT @info = Info
    FROM MyTable
    WHERE Id = @id
END

In that case, the Visual Studio static code analyzer produces the following error:

Warning : SR0007 : Microsoft.Performance : Nullable columns can cause final results to be evaluated as NULL for the predicate.

I don't see the problem here. The error is related to performance; MSDN says I should use ISNULL() -- but an equals comparison against NULL is always false, right? Am I missing something, or is the warning just wrong?

like image 818
RickNZ Avatar asked Feb 17 '26 17:02

RickNZ


2 Answers

I think it's referring to the WHERE clause. It's saying that both your parameter and your column can be NULL, in which case your WHERE clause no longer evaluates to true/false. By funneling your nullable column into one that always has a value defined (via ISNULL), you're in better shape, logic-wise.

Here's the Microsoft documentation on that error.

On the aside, NULLs supposedly make queries a skosh slower.

like image 173
Mark Canlas Avatar answered Feb 20 '26 10:02

Mark Canlas


I think the analyzer might just not be taking into account your IF statement.

Your code seems correct to me.

like image 28
Adriaan Stander Avatar answered Feb 20 '26 11:02

Adriaan Stander