Getting the next primary key without adding a new record is impossible, isn't it in MYSQL


No, it is possible to get the next primary key without adding a new record. Let us first create a −

mysql> create table DemoTable1399
   -> (
   -> StudentId int NOT NULL AUTO_INCREMENT,
   -> PRIMARY KEY(StudentId)
   -> );
Query OK, 0 rows affected (0.53 sec)

Insert some records in the table using insert −

mysql> insert into DemoTable1399 values();
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1399 values();
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1399 values();
Query OK, 1 row affected (0.07 sec)

Display all records from the table using select −

mysql> select * from DemoTable1399;

This will produce the following output −

+-----------+
| StudentId |
+-----------+
|         1 |
|         2 |
|         3 |
+-----------+
3 rows in set (0.00 sec)

Here is the query to get the next primary key without adding a new record −

mysql> select auto_increment as NextPrimaryKey
   -> from information_schema.tables
   -> where table_schema=database()
   -> and table_name = 'DemoTable1399';

This will produce the following output −

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

Updated on: 11-Nov-2019

38 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements