Implement MySQL INSERT MAX()+1?

MySQLMySQLi Database

You need to use COALESCE() function for this. The syntax is as follows:

INSERT INTO yourTableName(yourColumnName1,yourColumnName2)
SELECT 1 + COALESCE((SELECT MAX(yourColumnName1) FROM yourTableName WHERE yourColumnName2=’yourValue’), 0), ’yourValue’;

To understand the above syntax, let us create a table. The query to create a table is as follows:

mysql> create table InsertMaxPlus1Demo
   -> (
   -> Id int,
   -> Name varchar(20)
   -> );
Query OK, 0 rows affected (1.27 sec)

Now you can insert some records in the table using insert command. The query is as follows:

mysql> insert into InsertMaxPlus1Demo(Id,Name) values(1,'John');
Query OK, 1 row affected (0.12 sec)
mysql> insert into InsertMaxPlus1Demo(Id,Name) values(1,'Mike');
Query OK, 1 row affected (0.21 sec)
mysql> insert into InsertMaxPlus1Demo(Id,Name) values(2,'John');
Query OK, 1 row affected (0.12 sec)
mysql> insert into InsertMaxPlus1Demo(Id,Name) values(1,'Larry');
Query OK, 1 row affected (0.20 sec)
mysql> insert into InsertMaxPlus1Demo(Id,Name) values(3,'John');
Query OK, 1 row affected (0.18 sec)
mysql> insert into InsertMaxPlus1Demo(Id,Name) values(2,'David');
Query OK, 1 row affected (0.17 sec)

Display all records from table using select statement. The query is as follows:

mysql> select *from InsertMaxPlus1Demo;

The following is the output:

+------+-------+
| Id   | Name  |
+------+-------+
|    1 | John  |
|    1 | Mike  |
|    2 | John  |
|    1 | Larry |
|    3 | John  |
|    2 | David |
+------+-------+
6 rows in set (0.00 sec)

Here is the query to insert MAX()+1:

mysql> INSERT INTO InsertMaxPlus1Demo (Id, Name)
   -> SELECT 1 + coalesce((SELECT max(Id) FROM InsertMaxPlus1Demo WHERE Name='John'), 0), 'John';
Query OK, 1 row affected (0.21 sec)
Records: 1 Duplicates: 0 Warnings: 0

The above query is checking for John. It has the Id 3 and the record will be inserted with Id 4.

Now check the table record once again using select statement. The query is as follows:

mysql> select *from InsertMaxPlus1Demo;

The following is the output:

+------+-------+
| Id   | Name  |
+------+-------+
|    1 | John  |
|    1 | Mike  |
|    2 | John  |
|    1 | Larry |
|    3 | John  |
|    2 | David |
|    4 | John  |
+------+-------+
7 rows in set (0.00 sec)
raja
Published on 27-Feb-2019 06:42:29
Advertisements