Update two columns with a single MySQL query

MySQLMySQLi Database

For this, you need to use SET command only once. Let us first create a table −

mysql> create table DemoTable1909
   (
   Id int NOT NULL,
   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 DemoTable1909 values(101,'John','Smith');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1909 values(102,'John','Doe');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1909 values(103,'Adam','Smith');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1909 values(104,'David','Miller');
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1909;

This will produce the following output −

+-----+-----------+----------+
| Id  | FirstName | LastName |
+-----+-----------+----------+
| 101 | John      |    Smith |
| 102 | John      |      Doe |
| 103 | Adam      |    Smith |
| 104 | David     |   Miller |
+-----+-----------+----------+
4 rows in set (0.00 sec)

Here is the query to update two column values −

mysql> update DemoTable1909
     set FirstName='Carol',LastName='Taylor'
     where Id=103;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1 Warnings: 0

Let us check the table records once again −

mysql> select * from DemoTable1909;

This will produce the following output −

+-----+-----------+----------+
| Id  | FirstName | LastName |
+-----+-----------+----------+
| 101 | John      |    Smith |
| 102 | John      |      Doe |
| 103 | Carol     |   Taylor |
| 104 | David     |   Miller |
+-----+-----------+----------+
4 rows in set (0.00 sec)
raja
Published on 30-Dec-2019 10:57:33
Advertisements