Insert MAX(col)+1 into the same MySQL table?



Let us first create a table −

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

Insert some records in the table using insert command −

mysql> insert into DemoTable1484 values(100); Query OK, 1 row affected (0.25 sec) mysql> insert into DemoTable1484 values(175); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable1484 values(165); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable1484 values(145); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable1484 values(170); Query OK, 1 row affected (0.10 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1484;

This will produce the following output −

+------+ | Id   | +------+ |  100 | |  175 | |  165 | |  145 | |  170 | +------+ 5 rows in set (0.00 sec)

Here is the query to insert MAX(col)+1 into the same table −

mysql> insert into DemoTable1484(Id) select max(Id)+1 from DemoTable1484; Query OK, 1 row affected (0.20 sec) Records: 1  Duplicates: 0  Warnings: 0

Let us check the table records once again −

mysql> select * from DemoTable1484;

This will produce the following output. The new value inserted successfully −

+------+ | Id   | +------+ |  100 | |  175 | |  165 | |  145 | |  170 | |  176 | +------+ 6 rows in set (0.00 sec)
Updated on: 2019-12-10T08:15:01+05:30

615 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements