How MySQL SUM() function evaluates if the column having NULL values too?

MySQLMySQLi Database

Suppose if we are calculating the sum of the values of a column which also have NULL values then MySQL SUM() function ignores the NULL values and does the sum of the rest of the values. To understand it, consider the following example of table ‘employee’, having following details −

mysql> Select * from Employee;
+----+--------+--------+
| ID | Name   | Salary |
+----+--------+--------+
| 1  | Gaurav | 50000  |
| 2  | Rahul  | 20000  |
| 3  | Advik  | 25000  |
| 4  | Aarav  | 65000  |
| 5  | Ram    | 20000  |
| 6  | Mohan  | 30000  |
| 7  | Aryan  | NULL   |
| 8  | Vinay  | NULL   |
+----+--------+--------+
8 rows in set (0.00 sec)

Now, suppose if we want to have the total salary of the employees from above table then while calculating it with SUM() function, it ignores the NULL values. The following query will produce the required result set −

mysql> Select SUM(Salary) from Employee;
+-------------+
| SUM(Salary) |
+-------------+
| 210000      |
+-------------+
1 row in set (0.00 sec)

It can also be verified with the help of the following query −

mysql> Select SUM(Salary) from Employee WHERE Salary IS NOT NULL;
+-------------+
| SUM(Salary) |
+-------------+
|   210000    |
+-------------+
1 row in set (0.00 sec)
raja
Published on 21-Feb-2018 07:38:23
Advertisements