How MySQL evaluates if I will use an expression within SUM() function?

MySQLMySQLi Database

When we include an expression within SUM() function then MySQL evaluates it for each row of data and the total result is returned. To understand it, consider the following example of table ‘employee’, having the 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 know the total salary of the employees from the above table after deducting 1000 rupees from each employee’s salary then we can calculate it by using an expression within SUM() function, Following query will produce the required result set −

mysql> Select SUM(Salary-1000) from Employee;
+------------------+
| SUM(Salary-1000) |
+------------------+
|           204000 |
+------------------+
1 row in set (0.05 sec)
raja
Published on 21-Feb-2018 07:43:14
Advertisements