检查Date是否(非)为NULL或将某位与1/0进行比较是否更快?

Omu*_*Omu 11 sql sql-server performance

我只是想知道SQL(特别是SQL Server)的速度有多快.

我可以有一个类型为Date的可空列,并将其与之比较NULL,或者我可以有一个不可为空的Date列和一个单独的bit列,并将该bit列与1/ 进行比较0.

bit列的比较会更快吗?

Mar*_*ith 13

为了检查IS NULLSQL Server 列实际上只是检查了一点.为每一行存储了一个NULL BITMAP,指示每列是否包含NULL.

  • @ChuckNorris - 只要实际使用索引,查询索引会更快,因为SQL Server可以直接寻找感兴趣的行.如果`datetime`列本身已被索引,这也是如此. (2认同)

Cod*_*uth 10

I just did a simple test for this:

DECLARE @d DATETIME
        ,@b BIT = 0

SELECT 1
WHERE @d IS NULL

SELECT 2
WHERE @b = 0
Run Code Online (Sandbox Code Playgroud)

The actual execution plan results show the computation as exactly the same cost relative to the batch.

实际执行计划

Maybe someone can tear this apart, but to me it seems there's no difference.


MORE TESTS

SET DATEFORMAT ymd;

CREATE TABLE #datenulltest
(
    dteDate datetime NULL
)

CREATE TABLE #datebittest
(
    dteDate datetime NOT NULL,
    bitNull bit DEFAULT (1)
)

INSERT INTO #datenulltest ( dteDate )
SELECT  CASE WHEN CONVERT(bit, number % 2) = 1 THEN '2010-08-18' ELSE NULL END
FROM    master..spt_values

INSERT INTO #datebittest ( dteDate, bitNull )
SELECT  '2010-08-18', CASE WHEN CONVERT(bit, number % 2) = 1 THEN 0 ELSE 1 END
FROM    master..spt_values


SELECT  1
FROM    #datenulltest
WHERE   dteDate IS NULL

SELECT  2
FROM    #datebittest
WHERE   bitNull = CONVERT(bit, 1)


DROP TABLE #datenulltest
DROP TABLE #datebittest
Run Code Online (Sandbox Code Playgroud)

实际执行计划

dteDate IS NULL result:

IS NULL工具提示

bitNull = 1 result:

bitNull = 1

OK, so this extended test comes up with the same responses again.
We could do this all day - it would take some very complex query to find out which is faster on average.