{"id":277,"date":"2011-05-24T00:57:51","date_gmt":"2011-05-24T10:57:51","guid":{"rendered":"http:\/\/mymonkeydo.com\/?p=277"},"modified":"2011-05-24T00:57:51","modified_gmt":"2011-05-24T10:57:51","slug":"mysql-get-next-auto-increment-value","status":"publish","type":"post","link":"https:\/\/mymonkeydo.com\/mysql-get-next-auto-increment-value\/","title":{"rendered":"MySQL – Get Next Auto Increment Value"},"content":{"rendered":"
When adding an item to my mysql table, I needed to get the ID for the next inserted row. \u00a0The ID is just an auto increment column in the table. \u00a0At first I had:<\/p>\n
select max(table_id) + 1 as next_table_id from tablename<\/pre>\nI quickly realized how wrong that was. \u00a0When inserting ids 1, 2, 3, 4 and then deleting ID 4, my “next ID” query would return 4 instead of 5. \u00a0The MAX ID for a table\u00a0varies depending on what is currently in the table and is not a reliable source for the next inserted ID.<\/p>\n
<\/p>\n
Solution:<\/h2>\n
The query to use is:<\/p>\n
select auto_increment\nfrom information_schema.TABLES\nwhere TABLE_NAME='tablename'\nand TABLE_SCHEMA='basename'<\/pre>\n<\/p>\n
An alternative solution is to use<\/p>\n
SHOW TABLE STATUS WHERE name='tablename'<\/pre>\nI have seen some comments that “SHOW TABLE STATUS” is not transaction safe. \u00a0Although I cannot find that in the MySQL documents. \u00a0Also if the table is partitioned, the first query should be used as documented here<\/a>.<\/p>\n
<\/p>\n
<\/p>\n
<\/p>\n","protected":false},"excerpt":{"rendered":"","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_genesis_hide_title":false,"_genesis_hide_breadcrumbs":false,"_genesis_hide_singular_image":false,"_genesis_hide_footer_widgets":false,"_genesis_custom_body_class":"","_genesis_custom_post_class":"","_genesis_layout":"","footnotes":""},"categories":[5],"tags":[],"yoast_head":"\n
MySQL - Get Next Auto Increment Value - My Monkey Do<\/title>\n\n\n\n\n\n\n\n\n\n\n\n\t\n\t\n\t\n