To reserve MySQL auto-incremented IDs, the syntax is as follows −
START TRANSACTION; insert into yourTableName values(),(),(),(); ROLLBACK; SELECT LAST_INSERT_ID() INTO @anyVariableName;
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table reservingAutoIncrementDemo -> ( -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY -> ); Query OK, 0 rows affected (0.45 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> START TRANSACTION; Query OK, 0 rows affected (0.00 sec) mysql> insert into reservingAutoIncrementDemo values(),(),(),(); Query OK, 4 rows affected (0.15 sec) Records: 4 Duplicates: 0 Warnings: 0 mysql> select *from reservingAutoIncrementDemo; +--------+ | UserId | +--------+ | 1 | | 2 | | 3 | | 4 | +--------+ 4 rows in set (0.00 sec) mysql> rollback; Query OK, 0 rows affected (0.00 sec)
Here is the query to reserve the MySQL auto_incremented IDs −
mysql> SELECT LAST_INSERT_ID() INTO @IncrementedValue; Query OK, 1 row affected (0.00 sec)
Let us check the reserved auto_incremented value. The query is as follows −
mysql> select @IncrementedValue;
Here is the output −
+-------------------+ | @IncrementedValue | +-------------------+ | 1 | +-------------------+ 1 row in set (0.00 sec)