Reputation: 1401
Question: How can we correctly handle an arithmetic operation across different columns of a table where at least one of the operands is NULL?
Background: We have some data that was mined from the public domain and imported into MySQL. There are some text fields and some integer fields. The data miner treated all missing fields as NULL, rather than assign a value of 0 to the missing integer fields and NULL to the missing text fields.
I am able to recreate our issue with this simple table definition:
CREATE TABLE employee
(
id INT AUTO_INCREMENT,
name VARCHAR(40),
salary INT,
bonus INT,
PRIMARY KEY(id)
);
I am populating this sample table as follows
INSERT INTO employee(name, salary, bonus)
VALUES('Keith', 120000, 10000), ('Larson', 110000, 8000),
('Angelina', 125000, 12500), ('Will', 75000, null),
('Mary', 80000, null), ('Steve', null, null), ('John', null, null);
The query
SELECT * FROM employee;
yields
+----+----------+--------+-------+
| id | name | salary | bonus |
+----+----------+--------+-------+
| 1 | Keith | 120000 | 10000 |
| 2 | Larson | 110000 | 8000 |
| 3 | Angelina | 125000 | 12500 |
| 4 | Will | 75000 | NULL |
| 5 | Mary | 80000 | NULL |
| 6 | Steve | NULL | NULL |
| 7 | John | NULL | NULL |
+----+----------+--------+-------+
For arithmetic operations, the NULL values within a column are treated as 0s. That is why
SELECT SUM(salary) FROM employee;
yields
+-------------+
| SUM(salary) |
+-------------+
| 510000 |
+-------------+
However, when an arithmetic operation is performed across columns, and at least one of the operands is NULL, the value returned is NULL. For example:
SELECT name, (salary + bonus) FROM employee;
yields
+----------+------------------+
| name | (salary + bonus) |
+----------+------------------+
| Keith | 130000 |
| Larson | 118000 |
| Angelina | 137500 |
| Will | NULL |
| Mary | NULL |
| Steve | NULL |
| John | NULL |
+----------+------------------+
I would like my query to return 75000 for Will and 80000 for Mary (in addition to the correct values for Keith, Larson and Angelina).
Upvotes: 0
Views: 1664
Reputation: 847
You can use IFNULL.
SELECT
name,
salary + IFNULL(bonus, 0) as total
FROM employee;
Upvotes: 2
Reputation: 7503
use coalesce
. Here is the demo.
SELECT
name,
(salary + coalesce(bonus, 0)) as total
FROM employee;
output:
| name | total |
| -------- | ------ |
| Keith | 130000 |
| Larson | 118000 |
| Angelina | 137500 |
| Will | 75000 |
| Mary | 80000 |
| Steve | null |
| John | null |
On the safe side you can use (coalesce(salary, 0) + coalesce(bonus, 0))
, so your result won't show null
.
Upvotes: 2