- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Reserving MySQL auto-incremented IDs?
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)
Advertisements