How do I get the current AUTO_INCREMENT value for a table in MySQL?


To know the current auto_increment value, we can use the last_insert_id() function. Firstly, we will create a table with the help of INSERT command.

Creating a table −

mysql> CREATE table AutoIncrement
-> (
-> IdAuto int auto_increment,
-> primary key(IdAuto)
-> );
Query OK, 0 rows affected (0.59 sec)

After creating a table, we will insert the records with the help of INSERT command. Inserting records −

mysql> INSERT into AutoIncrement values();
Query OK, 1 row affected (0.48 sec)

mysql> INSERT into AutoIncrement values();
Query OK, 1 row affected (0.17 sec)

mysql> INSERT into AutoIncrement values();
Query OK, 1 row affected (0.13 sec)

mysql> INSERT into AutoIncrement values();
Query OK, 1 row affected (0.09 sec)

Now, we will see how many records have I inserted into my table with the help of SELECT command.

Displaying all records −

mysql> SELECT * from AutoIncrement;
+--------+
| IdAuto |
+--------+
| 1      |
| 2      |
| 3      |
| 4      |
+--------+
4 rows in set (0.00 sec)

Therefore, the last auto increment is 4. Here is the query to know the current value have inserted, which is 4.

mysql> SELECT last_insert_id();

The following is the output −

+------------------+
| last_insert_id() |
+------------------+
| 4                |
+------------------+
1 row in set (0.00 sec)

Here is the query that tells the next auto increment value. The syntax is as follows −

SELECT `AUTO_INCREMENT`
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'yourDatabaseName'
AND TABLE_NAME = 'yourTableName';

Now, I am applying the above query −

mysql> SELECT `AUTO_INCREMENT`
-> FROM INFORMATION_SCHEMA.TABLES
-> WHERE TABLE_SCHEMA = 'business'
-> AND TABLE_NAME = 'AutoIncrement';

The following is the output −

+----------------------------+
| AUTO_INCREMENT             |
+----------------------------+
| 5                          |
+----------------------------+
1 row in set (0.13 sec)

From the above query, we are getting the next increment value.

Updated on: 25-Jun-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements