Solved

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

Posted on 2014-11-16
3
94 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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 66

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

NFR key for Veeam Backup for Microsoft Office 365

Veeam is happy to provide a free NFR license (for 1 year, up to 10 users). This license allows for the non‑production use of Veeam Backup for Microsoft Office 365 in your home lab without any feature limitations.

Question has a verified solution.

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

Slowly Changing Dimension Transformation component in data task flow is very useful for us to manage and control how data changes in SSIS.
Recently we ran in to an issue while running some SQL jobs where we were trying to process the cubes.  We got an error saying failure stating 'NT SERVICE\SQLSERVERAGENT does not have access to Analysis Services. So this is a way to automate that wit…
Via a live example combined with referencing Books Online, show some of the information that can be extracted from the Catalog Views in SQL Server.
Via a live example, show how to setup several different housekeeping processes for a SQL Server.

707 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