Manisha Mishra
Manisha Mishra

Reputation: 11

Query with no records returns null for SUM function

This query will return you 0 records if no records exist in TableA:

Select strA, strB, intC, floatD, from tableA

However, this query returns 1 records with all columns as Null.

Select strA, strB, intC, floatD, sum(intC+intD) as sumE,
from tableA

So, to fix it, I did:

Select strA, strB, intC, floatD, sum(intC+intD) as sumE,
from tableA
having sumE is not null

I was wondering if there is a better way to do the same thing. Any in-built MySQL function that can do the same thing?

Upvotes: 1

Views: 757

Answers (1)

Tom H
Tom H

Reputation: 47444

That's because you don't have a GROUP BY. You're asking MySQL to get you the SUM of intC + intD for the entire table, so it's going to give you a result no matter what. It has to put in something for strA, strB, etc. so it puts in NULL values.

For example, just do SELECT SUM(intA) FROM tableA and you'll get NULL.

Upvotes: 3

Related Questions