Adding records with REPLACE INTO to mimic DELETE and INSERT


You can use REPLACE INTO that works like DELETE + INSERT. Let us first create a table −

mysql> create table DemoTable
(
   Id int,
   FirstName varchar(50)
);
Query OK, 0 rows affected (0.60 sec)

Following is the query to create a unique index −

mysql> alter table DemoTable add unique id_index(Id);
Query OK, 0 rows affected (0.41 sec)
Records: 0 Duplicates: 0 Warnings: 0

Insert some records in the table using insert command. Since we have added duplicate records, the new record gets added i.e. replaced with the same Id with the previous record −

mysql> replace into DemoTable values(100,'Chris');
Query OK, 1 row affected (0.10 sec)
mysql> replace into DemoTable values(101,'David');
Query OK, 1 row affected (0.13 sec)
mysql> replace into DemoTable values(100,'Bob');
Query OK, 2 rows affected (0.16 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+------+-----------+
| Id   | FirstName |
+------+-----------+
| 100  | Bob       |
| 101  | David     |
+------+-----------+
2 rows in set (0.00 sec)

Updated on: 01-Oct-2019

89 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements