Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SELECT SUM returns a row when there are no records

Tags:

sql

oracle

sum

I'm finding some problems with a query that returns the sum of a field from a table for all the records that meet certain conditions. I expected to receive a "No records found' when there were no records, but instead I'm receiving a null result.

SQL> SELECT * FROM DUAL WHERE 1=2;

no rows selected
SQL> SELECT SUM(dummy) FROM DUAL WHERE 1=2;

SUM(DUMMY)
----------


SQL>

Is there any way to not receive any record in that case?

like image 788
Jose L Martinez-Avial Avatar asked Mar 13 '10 02:03

Jose L Martinez-Avial


People also ask

How do you find the sum of zero if no records exist?

You can use aggregate function sum() inside COALESCE(). The below syntax returns the sum of all if the record exists otherwise 0 is returned.

Can SQL sum return null?

If there are no rows, sum() will return null . It will also return null if all rows have a null balance.

How do you sum zero queries in SQL?

To return Sum as '0' if no values are found, use IFNULL or COALESCE commands. The following is the syntax for IFNULL. SELECT IFNULL(SUM(NULL), 0) AS aliasName; Let us now implement the above syntax in the following query.

Can you sum a row in SQL?

If you need to add a group of numbers in your table you can use the SUM function in SQL. This is the basic syntax: SELECT SUM(column_name) FROM table_name; If you need to arrange the data into groups, then you can use the GROUP BY clause.


1 Answers

"I expected to receive a "No records found' when there were no records, but instead I'm receiving a null result."

Then do

SELECT SUM(dummy) FROM DUAL WHERE 1=2 HAVING COUNT(*) > 0

That is, specify that you only want to return a summary where there were rows that were considered.

SELECT SUM(dummy) FROM DUAL WHERE 1=2 HAVING SUM(dummy) IS NOT NULL

is similar, but the COUNT(*) would return a summary row if there were only rows for which dummy was null, while the latter would not.

like image 193
Gary Myers Avatar answered Sep 29 '22 23:09

Gary Myers