Reorder keys after deleting a record from MySQL table?


For this, use UPDATE command with some mathematical calculations. To delete an id, use the DELETE. Let us first create a table −

mysql> create table DemoTable1476
   -> (
   -> Id int
   -> );
Query OK, 0 rows affected (0.81 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1476 values(10);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable1476 values(20);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1476 values(30);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1476 values(40);
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1476;

This will produce the following output −

+------+
| Id   |
+------+
|   10 |
|   20 |
|   30 |
|   40 |
+------+
4 rows in set (0.00 sec)

Following is the query to delete some id from the table −

mysql> delete from DemoTable1476 where Id=30;
Query OK, 1 row affected (0.16 sec)

After deleting, the table records are as follows −

mysql> select * from DemoTable1476;

This will produce the following output −

+------+
| Id   |
+------+
|   10 |
|   20 |
|   40 |
+------+
3 rows in set (0.00 sec)

Following is the query to reorder keys after deleting from MySQL table −

mysql> update DemoTable1476 set Id=Id-10 where Id > 30;
Query OK, 1 row affected (0.14 sec)
Rows matched: 1  Changed: 1 Warnings: 0

Let us check the table records once again −

mysql> select * from DemoTable1476;

This will produce the following output −

+------+
| Id   |
+------+
|   10 |
|   20 |
|   30 |
+------+
3 rows in set (0.00 sec)

Updated on: 10-Dec-2019

368 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements