什么是更快:SUM超过NULL或超过0?

时间:2015-11-25 12:04:56

标签: sql-server sql-server-2008-r2 sql-server-2012 query-performance

我有这样的查询:

select sum(case when col1=@arg1 then value else null end) from t

使用0代替NULL是否存在性能方面的差异?像这样:

select sum(case when col1=@arg1 then value else 0 end) from t

2 个答案:

答案 0 :(得分:4)

DECLARE @type CHAR(2) = 'U'

-- [Expr1042] = Scalar Operator(CASE WHEN [Expr1048]=(0) THEN NULL ELSE [Expr1049] END)

SELECT SUM(CASE WHEN [type] = @type THEN 1 END)
FROM sys.objects

-- [Expr1042] = Scalar Operator(CASE WHEN [Expr1048]=(0) THEN NULL ELSE [Expr1049] END)

SELECT SUM(CASE WHEN [type] = @type THEN 1 ELSE NULL END)
FROM sys.objects

-- [Expr1042] = Scalar Operator(CASE WHEN [Expr1048]=(0) THEN NULL ELSE [Expr1049] END)

SELECT SUM(CASE WHEN [type] = @type THEN 1 ELSE 0 END)
FROM sys.objects

结果:

Table 'sysschobjs'. Scan count 1, logical reads 1556, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
 SQL Server Execution Times:
   CPU time = 0 ms,  elapsed time = 7 ms.

Table 'sysschobjs'. Scan count 1, logical reads 1556, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
 SQL Server Execution Times:
   CPU time = 0 ms,  elapsed time = 6 ms.

Table 'sysschobjs'. Scan count 1, logical reads 1556, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
 SQL Server Execution Times:
   CPU time = 0 ms,  elapsed time = 7 ms.

所以...回答 - 类似(如果我们只谈论表现)

答案 1 :(得分:3)

在下面的测试中,我始终发现NULL稍快一些。

   SET STATISTICS TIME ON;
   DECLARE @i int = null; /*Or set to zero*/

   WITH 
    E1(N) AS 
    (
        SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL 
        SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL 
        SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
    )                                       -- 1*10^1 or 10 rows
    , E2(N) AS (SELECT 1 FROM E1 a, E1 b)   -- 1*10^2 or 100 rows
    , E4(N) AS (SELECT 1 FROM E2 a, E2 b)   -- 1*10^4 or 10,000 rows
    , E8(N) AS (SELECT 1 FROM E4 a, E4 b)   -- 1*10^8 or 100,000,000 rows

    SELECT SUM(@i) FROM E8 
    OPTION (MAXDOP 1)

平均608ms汇总100,000,000个值。 (即每个聚合6纳秒)。

NULL花费更多时间在

sqllang.dll!CESRunTimeErrorSink::SetAggFnSkippedNull

大概设置导致消息的标志

  

警告:聚合或其他SET消除了空值   操作

但总的来说似乎更快(以下ms的经过时间)。

+---------+--------+------++-------+
|         |  NULL  |  0   || Diff  |
+---------+--------+------++-------+
| Trial 1 | 7027   | 7592 || 565   |
| Trial 2 | 6981   | 7743 || 762   |
| Trial 3 | 7451   | 8015 || 564   |
| Trial 4 | 6997   | 7591 || 594   |
| Trial 5 | 7018   | 7574 || 556   |
+---------+--------+------++-------+
| Avg     | 7094.8 | 7703 || 608.2 |
+---------+--------+------++-------+

当然在这种情况下(所有输入都是NULL),它们会返回不同的结果,如果您想要互换地处理这两个结果,则需要ISNULL(SUM(@i),0)