Difference between ISNULL(SUM(x),0) OR SUM(ISNULL(x,0) in SQL server
sql-server, sql-server-2008
Solution
They both return the same except if you are running a query on an empty result set.
WITH Sales(Sales) AS
(
SELECT 1
)
SELECT
SUM(ISNULL(Sales,0)) AS Sales,
ISNULL(SUM(Sales),0) AS Sales
FROM Sales
WHERE 1=0
Returns
Sales Sales
----------- -----------
NULL 0
The `SUM(ISNULL(Sales,0))` version would avoid the ANSI WARNINGS about aggregating `NULL`.
One other subtle difference is that the datatype of the result column of `ISNULL(SUM(Sales),0)` is not regarded as nullable.
Problem
Which one of the following is correct? ``` SUM(ISNULL(Sales,0)) AS Sales, ISNULL(SUM(Sales),0) AS Sales, ``` Or are they both correct?