Home > Database > Mysql Tutorial > body text

How to get the next auto-increment ID in MySQL?

WBOY
Release: 2023-08-22 22:29:05
forward
2232 people have browsed it

How to get the next auto-increment ID in MySQL?

MySQL has the AUTO_INCREMENT keyword to perform automatic increment. The starting value of AUTO_INCREMENT is 1, which is the default value. It will be incremented by 1 for every new record.

To get the next automatically incremented id in MySQL, we can use MySQL's last_insert_id() function or auto_increment in the SELECT statement.

Create a table in which "id" is auto-incremented.

mysql> create table NextIdDemo
   -> (
   -> id int auto_increment,
   -> primary key(id)
   -> );
Query OK, 0 rows affected (1.31 sec)
Copy after login

Insert records into the table.

mysql> insert into NextIdDemo values(1);
Query OK, 1 row affected (0.22 sec)

mysql>  insert into NextIdDemo values(2);
Query OK, 1 row affected (0.20 sec)

mysql>  insert into NextIdDemo values(3);
Query OK, 1 row affected (0.14 sec)
Copy after login

Display all records.

mysql> select *from NextIdDemo;
Copy after login

The following is the output result.

+----+
| id |
+----+
|  1 |
|  2 |
|  3 |
+----+
3 rows in set (0.04 sec)
Copy after login

We inserted 3 records above. Therefore, the next id must be 4.

The following is the syntax to understand the next id.

SELECT AUTO_INCREMENT
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = "yourDatabaseName"
AND TABLE_NAME = "yourTableName"
Copy after login

The following is the query.

mysql> SELECT AUTO_INCREMENT
    -> FROM information_schema.TABLES
    -> WHERE TABLE_SCHEMA = "business"
    -> AND TABLE_NAME = "NextIdDemo";
Copy after login

Here is the output showing the next automatic increment.

+----------------+
| AUTO_INCREMENT |
+----------------+
|              4 |
+----------------+
1 row in set (0.25 sec)
Copy after login

The above is the detailed content of How to get the next auto-increment ID in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template