How can I insert a value in a column at the place of NULL using MySQL COALESCE() function?


To understand it, we are using the data from the table ‘Employee’ having Salary=NULL for ID = 5 and 6, as follows −

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

Now, the following queries will use COALESCE() function along with UPDATE and WHERE clause to put values at the place of NULL.

mysql> Update Employee set Salary = COALESCE(Salary,20000) where Id = 5;
Query OK, 1 row affected (0.09 sec)
Rows matched: 1 Changed: 1 Warnings: 0

mysql> Update Employee set Salary = COALESCE(Salary,30000) where Id = 6;
Query OK, 1 row affected (0.06 sec)
Rows matched: 1 Changed: 1 Warnings: 0

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  |
+----+--------+--------+
6 rows in set (0.00 sec)

Updated on: 20-Jun-2020

563 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements