3

How to select the last insert id from database table

i need to get the last insert id from database

i try the last_insert_id() function but this doesn't work for me because i want to get this id before i do an insert query and when i get this id i do an insert query

i try to use max for the id but this have a problem that if i have a deleted id it will not be taken

example if i have id 10 deleted than the max id will be 9 but the auto increment will be 11

than i want to have the new id that will be added by the auto increment

example:i have an id 10 deleted i want to take than next id it will be 11

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
mohamad mohamad
  • 613
  • 9
  • 24

3 Answers3

5

You Can :

    SELECT AUTO_INCREMENT
    FROM  INFORMATION_SCHEMA.TABLES
    WHERE TABLE_SCHEMA = 'database_name'
    AND   TABLE_NAME   = 'table_name';
And get your last id.
ahammar
  • 282
  • 1
  • 14
  • what i information_schema.tables what is table_schema ? – mohamad mohamad Sep 16 '16 at 10:38
  • INFORMATION_SCHEMA is a database come with mysql by default [check mysql doc](http://dev.mysql.com/doc/refman/5.7/en/information-schema.html), you will find the info that you want, why not execute it instead of setting a -1 – ahammar Sep 16 '16 at 10:47
1

The autoincrement value is generated by the database itself, when the insertion is done ; which means you cannot get it before doing the actual insert query. insert some half-empty data get the autoincrement value that's been generated do your calculations, using that autoincrement value update the row to put the new / full data in place -- using the autoincrement generated earlier in the where clause of the update query, to identify which row is being updated.

As pseudo-code :
begin transaction
insert into your table (half empty values);
$id = get last autoincrement id
do calculations
update set data = full data where id = $id
commit transaction

or you may follow Using Auto-Increment value in MYSQL Before Insert Trigger?

Community
  • 1
  • 1
G San
  • 81
  • 6
  • `which means you cannot get it before doing the actual insert query` isn't correct.. See ahammar's answer... – Fipsi Aug 10 '19 at 10:00
0

You can not and should not get the last inserted id before insert.

And there is not a single reason to do so. Just insert your data, get the actual id, and use it anywhere else. As simple as that.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345