Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I retrieve the last inserted value in my database?

Can anybody tell me the query for last inserted value in the column of the database.

The problem is that inserted value can be placed in inner rows of the database after using ASC or DESC so I cant use the method. If anybody has the solution please tell me.

like image 756
Durvesh Avatar asked Jul 13 '12 16:07

Durvesh


People also ask

How can we get last inserted data from database?

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 you get the last inserted identity value?

Use @@IDENTITY to Return the Last-Inserted Identity Value in SQL Server. 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 get the last inserted ID in SQL query?

IDENT_CURRENT() will give you the last identity value inserted into a specific table from any scope, by any user. @@IDENTITY gives you the last identity value generated by the most recent INSERT statement for the current connection, regardless of table or scope.


1 Answers

You will need to use a TIMESTAMP data column in order to keep track of insertion time. Unfortunately, due to inherent race conditions, using auto-incrementing primary keys will not work in this case. Simply add the entry timestamp as a data column and retrieve with ORDER BY time_stamp DESC LIMIT 1 to get the last record. If you're feeling really defensive, aim to include conditions in the WHERE clause that are unique to the original INSERT call (i.e., WHERE ID = x AND KEY = y)

like image 177
Daniel Li Avatar answered Oct 15 '22 19:10

Daniel Li