New related comments
Number of comments in the last 48 hours
Location of mysql startup script
Best operating system settings for mysql throughput
Monitoring mysql status
How can I obtain the next auto_increment number (before inserting a record)?
1 comments. Current rating: (1 votes). Leave comments and/ or rate it.
Question:How can I obtain the next auto_increment number (before inserting a record)?
Answer:At first glance you might think to use select MAX(..) to obtain the most recent number and add one.. but that would not work if the most recent row got deleted or if there are two concurrent transactions.
It is not possible to do obtain the next value of an AUTO_INCREMENT field but you can use a little trick:
Let's say you have a table CUSTOMERS with a unique CUST_ID which is an auto_increment integer.
Change this to be a unique integer (no auto_increment) and create a second helper table CUSTOMER_IDS.
This second table has only the purpose to deliver a new unique number. In order for this to work, you'll always have to use this helper table whenever a row is inserted into your main table CUSTOMERS.
When you want to find out what the next number will be, you can use LAST_INSERT_ID() on that helper table. For more details read the documentation on this function.