Home > Database > Mysql Tutorial > How to Avoid NULL SUM Return in MySQL?

How to Avoid NULL SUM Return in MySQL?

Patricia Arquette
Release: 2024-11-01 22:16:30
Original
345 people have browsed it

How to Avoid NULL SUM Return in MySQL?

How to Avoid NULL SUM Issue in MySQL

In MySQL, the SUM function can return NULL if no values are found. This can be problematic when you want the function to return 0 instead.

Situation

Consider the following query:

SELECT SUM(Column_1)
FROM Table
WHERE Column_2 = 'Test'
Copy after login

If no entries in Column_2 contain the text 'Test', the function returns NULL.

Solution: Using COALESCE

To avoid this issue, you can use the COALESCE function. COALESCE takes two arguments: a value and a default value. If the value is NULL, COALESCE returns the default value.

Here's how you can use COALESCE with SUM:

SELECT COALESCE(SUM(Column_1), 0)
FROM Table
WHERE Column_2 = 'Test'
Copy after login

Now, if no entries in Column_2 contain the text 'Test', the function will return 0 instead of NULL.

Example

You can see this in action in the SQL Fiddle here: http://www.sqlfiddle.com/#!2/d1542/3/0

This example demonstrates how COALESCE can be used to return 0 when no values are found in a SUM function.

Additional Information

The COALESCE function can be used with any value or expression. It's a versatile tool that can be used to handle NULL values in various situations.

The above is the detailed content of How to Avoid NULL SUM Return in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template