

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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)
- Related Questions & Answers
- Query MySQL database to echo highest auto incremented number?
- How to insert data to MySQL having auto incremented primary key?
- How to set the initial value of an auto-incremented column in MySQL using JDBC?
- How to retrieve auto-incremented value generated by PreparedStatement using JDBC?
- How to retrieve auto-incremented value generated by Statement using JDBC?
- How to insert data into a table with auto-incremented columns using JDBC?
- Order MySQL query by multiple ids?
- Update table with duplicate ids in MySQL
- How to set different auto-increment ids for two tables with a user-defined variable?
- Passing Multiple ids to single parameter in MySQL?
- Compare two tables and return missing ids in MySQL?
- Display IDs in a particular order with MySQL IN()?
- Display highest amount from corresponding duplicate ids in MySQL
- Change the Auto Increment counter in MySQL?
- Passing NULL to MySQL for auto increment?
Advertisements