Update a column A if null, else update column B, else if both columns are not null do nothing with MySQL



For this, use IF() with IS NULL property. Let us first create a table −

mysql> create table DemoTable1976    (    FirstName varchar(20),    LastName varchar(20)    ); Query OK, 0 rows affected (0.00 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1976 values('John','Doe'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1976 values('John',NULL); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1976 values(NULL,'Miller'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1976 values('Chris','Brown'); Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1976;

This will produce the following output −

+-----------+----------+ | FirstName | LastName | +-----------+----------+ | John      |      Doe | | John      |     NULL | | NULL      |   Miller | | Chris     |    Brown | +-----------+----------+ 4 rows in set (0.00 sec)

Here is the query to update a column if null else update anther column, else if both columns are not null do nothing −

mysql> update DemoTable1976    set FirstName=if(FirstName IS NULL,'David',FirstName),    LastName=if(LastName IS NULL,'Brown',LastName); Query OK, 2 rows affected (0.00 sec) Rows matched: 4  Changed: 2 Warnings: 0

Let us check the table records once again −

mysql> select * from DemoTable1976;

This will produce the following output −

+-----------+----------+ | FirstName | LastName | +-----------+----------+ | John      |      Doe | | John      |    Brown | | David     |   Miller | | Chris     |    Brown | +-----------+----------+ 4 rows in set (0.00 sec)
Updated on: 2019-12-31T07:59:15+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements