8

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.

Jonas
  • 121,568
  • 97
  • 310
  • 388
Xperiaz X
  • 216
  • 1
  • 6
  • 16
  • neither. I want to receive a value. But these answers print a description. Not a retrievable value – Xperiaz X Aug 12 '13 at 11:32
  • http://www.microshell.com/database/mysql/emulating-nextval-function-to-get-sequence-in-mysql/ – Mihai Aug 12 '13 at 13:15
  • USE THIS CODE: `SELECT (IFNULL(max(id),0) + 1 ) as id from table`. IFNULL will be helpful if there is no record in the table – Eugine Joseph Sep 28 '13 at 08:05

3 Answers3

9

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

Flash Thunder
  • 11,672
  • 8
  • 47
  • 91
1

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();
Mihai
  • 26,325
  • 7
  • 66
  • 81
0

There is no way to guarantee what value you are going to get before inserting the row. This is mostly because you will have to lock the entire table to guarantee no other thread will do an insert with "your" next value.

You can reserve a value by starting a transaction, inserting a row, getting the value and then doing a rollback. Then you can safely use that value.

It will be much simpler to just insert the row, so maybe I'm not understanding the purpose of what you are doing.

Vatev
  • 7,493
  • 1
  • 32
  • 39
  • I want to perform insert query into another table, check if it is valid, and only then insert into this table. – Xperiaz X Aug 12 '13 at 11:28
  • The best way to do that would be a transaction. If you are using MyISAM the best I can think of is to insert the row, get the autoincrement value, , if it fails delete the row. – Vatev Aug 12 '13 at 12:02