Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Last inserted id from specific table

Tags:

mysql

SELECT LAST_INSERT_ID() as id FROM table1

Why does this query sometimes return the last inserted id of another table other than table1? I call it in Node.js (db-mysql plugin) and I can only do queries.

like image 712
ElSajko Avatar asked Aug 25 '12 20:08

ElSajko


People also ask

How do I get the last insert ID from a specific table?

If you are AUTO_INCREMENT with column, then you can use last_insert_id() method. This method gets the ID of the last inserted record in MySQL. Insert some records in the table using insert command. Display all records from the table using select statement.

How do I get the last inserted ID in SQL?

MySQL LAST_INSERT_ID() Function The LAST_INSERT_ID() function returns the AUTO_INCREMENT id of the last row that has been inserted or updated in a table.

How do you retrieve the last identity value that is generated?

In SQL Server, you can use the T-SQL @@IDENTITY system function to return the last-inserted identity value in the current session. Note that it returns the last identity value generated in any table in the current session.

How do I find the last ID of a database?

How to get last inserted id of a MySQL table using LAST_INSERT_ID() We will be using the LAST_INSERT_ID() function to get the last inserted id. Last_insert_id() MySQL function returns the BIG UNSIGNED value for an insert statement on an auto_increment column.


2 Answers

LAST_INSERT_ID() can only tell you the ID of the most recently auto-generated ID for that entire database connection, not for each individual table, which is also why the query should only read SELECT LAST_INSERT_ID() - without specifying a table.
As soon as you fire off another INSERT query on that connection, it gets overwritten. If you want the generated ID when you insert to some table, you must run SELECT LAST_INSERT_ID() immediately after doing that (or use some API function which does this for you).

If you want the newest ID currently in an arbitrary table, you have to do a SELECT MAX(id) on that table, where id is the name of your ID column. However, this is not necessarily the most recently generated ID, in case that row has been deleted, nor is it necessarily one generated from your connection, in case another connection manages to perform an INSERT between your own INSERT and your selection of the ID.

(For the record, your query actually returns N rows containing the most recently generated ID on that database connection, where N is the number of rows in table1.)

like image 179
Michael Madsen Avatar answered Sep 30 '22 06:09

Michael Madsen


SELECT id FROM tableName ORDER BY id DESC LIMIT 1

like image 38
Hitesh Avatar answered Sep 30 '22 07:09

Hitesh