Update table with duplicate ids in MySQL


Following is the syntax −

update yourTableName set yourColumnName1= yourValue where yourColumnName2=yourValue order by yourColumnName2 DESC LIMIT 1;

Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Id int,
   -> Name varchar(100)
   -> );
Query OK, 0 rows affected (0.61 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(1,'John');
Query OK, 1 row affected (0.41 sec)

mysql> insert into DemoTable values(2,'Chris');
Query OK, 1 row affected (0.15 sec)

mysql> insert into DemoTable values(2,'Robert');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable values(2,'David');
Query OK, 1 row affected (0.18 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

+------+--------+
| Id   | Name   |
+------+--------+
|    1 | John   |
|    2 | Chris  |
|    2 | Robert |
|    2 | David  |
+------+--------+
4 rows in set (0.00 sec)

Following is the query to update table in SQL WHERE clause multiple fields −

mysql> update DemoTable set Name='Adam Smith' where Id=2 order by Id DESC LIMIT 1;
Query OK, 1 row affected (0.28 sec)
Rows matched: 1  Changed: 1 Warnings: 0

Let us check table records once again −

mysql> select *from DemoTable;

Output

+------+------------+
| Id   | Name       |
+------+------------+
|    1 | John       |
|    2 | Adam Smith |
|    2 | Robert     |
|    2 | David      |
+------+------------+
4 rows in set (0.00 sec)

Updated on: 30-Jul-2019

444 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements