How can I customize value, instead of NULL, of a row by using MySQL IF() function?


Suppose in our ‘Employee’ table we are having NULL as the value of ‘salary’ column for two employees. The data, shown as follows, is itself not meaningful.

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.22 sec)

We can avoid displaying NULL in the output by using the IF() function to return ‘N/A’ instead of NULL.

mysql> Select ID,Name,IF(Salary IS NULL, 'N/A',Salary) As 'Salary' 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  | N/A    |
| 8  | Vinay  | N/A    |
+----+--------+--------+
8 rows in set (0.00 sec)

Updated on: 11-Feb-2020

44 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements