SQL Server return Rows that are not equal <> to a value and NULL

落爺英雄遲暮 提交于 2019-12-08 14:35:49

问题


I have a table that has a column of values that can be rowTypeID = (1,2,3, or null) . I would like to write a query that returns any row that doesn't have a value of 3 in it. In this example I want all NULL rows along with all 1,2 rows I just don't want rows with the value of 3

Set ANSI null ON is currently set for the database.

I'm curious as to why I can't write

select * from myTable where myCol <> 3

This query will not return any rows that have NULL in the myCol column

I have to write

select * from my Table where myCol <> 3 or myCol Is NULL 

Do I always have to include the IS NULL or can I set it up so a where clause myCol <>3 will return rows that have Null as value for my Col


回答1:


I think your approach is fine:

SELECT *
FROM MyTable
WHERE myCol <> 3 OR myCol IS NULL

Since you are asking for alternatives, another way to do it is to make your column NOT NULL and store another (otherwised unused) value in the database instead of NULL - for example -1. Then the expression myCol <> 3 will match your fake-NULL just as it would with any other value.

SELECT *
FROM MyTable
WHERE myCol <> 3

However in general I would recommend not to use this approach. The way you are already doing it is the right way.

Also it might be worth mentioning that several other databases support IS DISTINCT FROM which does exactly what you want:

SELECT *
FROM MyTable
WHERE myCol IS DISTINCT FROM 3

MySQL has the NULL-safe equal which can also be used for this purpose:

SELECT *
FROM MyTable
WHERE NOT myCol <=> 3

Unfortunately SQL Server doesn't yet support either of these syntaxes.




回答2:


You must handle the NULLs one way or another, since expressions involving NULL evaluate to Unknown. If you want, you could instead do:

select *
from MyTable
where isnull(MyColumn, -1) <> 3

But this involves a magic number (-1), and is arguably less readable than the original test for IS NULL.

Edit: and, as SQLMenace points out, is not SARGable.




回答3:


Whenever you test for a value all NULLs are omitted – after all, you are testing whether the value in some column passes certain criteria and NULL is not a value.




回答4:


Do I always have to include the IS NULL or can I set it up so a where clause myCol <>3 will return rows that have Null as value for my Col?

You always, always, always have to include is null.

Because 3 does not equal Not/Applicable and it does not equal Unkown.




回答5:


because you can't compare NULL to anything else, NULL is not even equal to NULL

DECLARE @i INT
DECLARE @i2 INT

SELECT @i = NULL, @i2 = NULL

IF @i = @i2
PRINT 'equal'
ELSE 
PRINT 'not equal'


来源:https://stackoverflow.com/questions/4453622/sql-server-return-rows-that-are-not-equal-to-a-value-and-null

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!