How MySQL evaluates when I use a conditional expression within SUM() function?


As we know that, by using a conditional expression within SUM() function we can get the number of rows that meet the condition. So, in this case, MySQL evaluates to 1 each time the condition is true and 0 each time it is false.

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 number of rows having a salary more than 20000 then the conditional expression can be used within SUM() function as follows −

mysql> Select SUM(Salary>20000) from employee568;
+-------------------+
| SUM(Salary>20000) |
+-------------------+
|                 4 |
+-------------------+
1 row in set (0.00 sec)

The above result set shows that 4 employees are getting more than 20000 salaries.

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 22-Jun-2020

78 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements