Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is faster: SUM over NULL or over 0?

I have a query like this:

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

Is there, performance-wise, a difference to use 0 instead of NULL ? Like this:

select sum(case when col1=@arg1 then value else 0 end) from t
like image 465
SQL Police Avatar asked Nov 25 '15 12:11

SQL Police


People also ask

Does Sum work with NULL?

In MySQL, SUM() is supposed to ignore null values. In any case, if you want to be specific, you can instruct the SQL Optimiser to substitute the null values with the value of 0.

Which is faster sum or count?

Question: What is Faster, SUM or COUNT? Answer: Both are the same.

Does zero count as NULL?

The answer to that is rather simple: a NULL means that there is no value, we're looking at a blank/empty cell, and 0 means the value itself is 0. Considering there is a difference between NULL and 0, the way Tableau treats these two values therefore is different as well.

Does sum ignore NULL values MySQL?

If you use the SUM() function in a SELECT statement that returns no row, the SUM() function returns NULL , not zero. The DISTINCT option instructs the SUM() function to calculate the sum of only distinct values in a set. The SUM() function ignores the NULL values in the calculation.


1 Answers

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

results:

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.

so... answer - similar (if we talk only about performance)

like image 174
Devart Avatar answered Nov 02 '22 13:11

Devart