Which one of the following is correct?
SUM(ISNULL(Sales,0)) AS Sales,
ISNULL(SUM(Sales),0) AS Sales,
Or are they both correct?
SELECT SUM(ISNULL(Salary, 10000) AS Salary FROM Employee; Output: In MySQL, ISNULL() function is used to test whether an expression is NULL or not. If the expression is NULL it returns TRUE, else FALSE.
You wrap the SUM with an ISNULL, ISNULL(Sum(Ac_Billbook. CostsNet), 0) because SUM ignores nulls when summing or you can reverse the SUM and ISNULL like this, Sum(ISNULL(Ac_Billbook. CostsNet, 0)) which will convert individual NULL's to 0. Doesn't really matter which one you do.
Example 4: Difference between SQL Server ISNULL with IS NULL You might confuse between SQL Server ISNULL and IS NULL. We use IS NULL to identify NULL values in a table. For example, if we want to identify records in the employee table with NULL values in the Salary column, we can use IS NULL in where clause.
SUM can be used with numeric columns only. Null values are ignored.
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.
The first one says
SUM up every Sales field, and if the field is NULL, treat it as zero.
The second says Sum up the sales field, and if the total is NULL, report a zero instead...
However, the SUM() command skips NULL (although you'll be warned about it), so the first one will cause you not to get the error message
Try this:
DECLARE @table TABLE
(
id INT IDENTITY,
Alborz INT
)
INSERT INTO @table
SELECT 1
UNION ALL
SELECT 1
UNION ALL
SELECT 1
UNION ALL
SELECT 1
UNION ALL
SELECT 1
UNION ALL
SELECT NULL
SELECT ISNULL(SUM(Alborz), 0)
FROM @table
SELECT SUM(ISNULL(Alborz, 0))
FROM @table
DELETE FROM @table
SELECT ISNULL(SUM(Alborz), 0)
FROM @table
SELECT SUM(ISNULL(Alborz, 0))
FROM @table
You'll get 21, 21, 0, and NULL. If you don't want to handle nulls, then ISNULL(SUM(X),0) is the way to go.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With