Solved

Why is Null the result for a Sum calculation on a record not found

Posted on 2014-11-16
3
90 Views
Last Modified: 2014-11-16
For the below code why would the result return 1 row and a value of Null for SUM ?  In my case StockID 25 does not exist so  my assumption is that no rows would  be found ?  Why is 1 row returned ?


Select
 SUM(Interest) As Total
From
Table Stocks
WHERE
StockID = 25
0
Comment
Question by:upobDaPlaya
3 Comments
 
LVL 3

Accepted Solution

by:
Richard Obenchain earned 500 total points
ID: 40446212
No rows are found, but you're doing an aggregate without a group by statement, which means you'll always get one row result (regardless of whether there was anything to add up or not).

If you don't want any row to return, you could do this:

Select stockid, sum(interest) as Total where stockid = 25 group by stockid;

Because of the grouping, it won't return any rows unless there are valid records for Stockid = 25
0
 

Author Closing Comment

by:upobDaPlaya
ID: 40446231
Perfect.  Thanks for the explanation.  Makes total sense.
0
 
LVL 65

Expert Comment

by:Jim Horn
ID: 40446239
>For the below code why would the result return 1 row and a value of Null for SUM ?
As Richard states above now rows are found, and think of it this way:  NULL means there no rows found, and zero means rows were found and the average is zero.  These are two completely different answers, which could have erroneous downstream impacts if a zero is passed.
0

Featured Post

Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
sql 2014,  lock limit 5 32
SQL SELECT query help 7 41
Sql Server group by 10 29
T-SQL: New to using transactions 9 30
I wrote this interesting script that really help me find jobs or procedures when working in a huge environment. I could I have written it as a Procedure but then I would have to have it on each machine or have a link to a server-related search that …
For both online and offline retail, the cross-channel business is the most recent pattern in the B2C trade space.
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question