Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find next value of AUTO_INCREMENT column in MySQL [duplicate]

I am using MySQL. I want to retrieve the next value that the AUTO_INCREMENT column will take without entering a new record.

create table ABC(id int(10) NOT NULL AUTO_INCREMENT,name char(10));

In oracle I would have used sequencename.nextval(); But what to I use in MySQL?

Here is why I did not use

select max(id) from ABC;

Suppose I have an entry with id=2. Now column id will take the next value as 3. Before I create a record with id=3, If I delete the record with id=2. The answer for query I mentioned will be 2. But I want the actual value 3, which the auto_increment column will anyway take.

like image 503
Xperiaz X Avatar asked Aug 12 '13 11:08

Xperiaz X


People also ask

How do I get the next autoincrement value in SQL?

MySQL has the AUTO_INCREMENT keyword to perform auto-increment. The starting value for AUTO_INCREMENT is 1, which is the default. It will get increment by 1 for each new record. To get the next auto increment id in MySQL, we can use the function last_insert_id() from MySQL or auto_increment with SELECT.

Where is auto increment column in MySQL?

In MySQL, the syntax to change the starting value for an AUTO_INCREMENT column using the ALTER TABLE statement is: ALTER TABLE table_name AUTO_INCREMENT = start_value; table_name. The name of the table whose AUTO_INCREMENT value you wish to change.

How is auto increment value calculated?

To know the current auto_increment value, we can use the last_insert_id() function.

How can I get auto increment value after insert?

To obtain the value immediately after an INSERT , use a SELECT query with the LAST_INSERT_ID() function. For example, using Connector/ODBC you would execute two separate statements, the INSERT statement and the SELECT query to obtain the auto-increment value.


2 Answers

Query table status like this:

SHOW TABLE STATUS WHERE `Name` = 'table_name'

Now in result you will get a column named Auto_increment. This is the value You were asking for.

In JAVA:

conn = DriverManager.getConnection(connectionUrl, connectionUser, connectionPassword);
stmt = conn.createStatement();
rs = stmt.executeQuery("SHOW TABLE STATUS WHERE `Name` = 'table_name'");
rs.next();
String nextid = rs.getString("Auto_increment");

Full example here: http://www.avajava.com/tutorials/lessons/how-do-i-use-jdbc-to-query-a-mysql-database.html

like image 110
Flash Thunder Avatar answered Oct 14 '22 04:10

Flash Thunder


If I understand correctly,you could use the number of rows as indicator:

SELECT TABLE_ROWS+1
FROM information_schema.tables 
WHERE table_name='tableName'
AND table_schema = DATABASE();
like image 44
Mihai Avatar answered Oct 14 '22 03:10

Mihai