
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Update Column A or B in MySQL Based on Conditions
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)
Advertisements