createtableNextIdDemo->(->idintauto_increment,->primarykey(id)->);"/> createtableNextIdDemo->(->idintauto_increment,->primarykey(id)->);">

Home >Database >Mysql Tutorial >How to get the next auto-increment ID in MySQL?

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

WBOY
WBOYforward
2023-08-22 22:29:052265browse

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)

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)

Display all records.

mysql> select *from NextIdDemo;

The following is the output result.

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

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"

The following is the query.

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

Here is the output showing the next automatic increment.

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

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete