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.
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.
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.
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 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.
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
.)
SELECT id FROM tableName ORDER BY id DESC LIMIT 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With