简体   繁体   中英

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.

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 (ie, WHERE ID = x AND KEY = y )

I second @Daniel Li's comments.

In every persistent table that I create, I have the following columns:

  • id which is the first column and auto-incremented/identity/serial column
  • CreatedBy which defaults to the user ("default system_user" in SQL Server) so I know who updated the column
  • CreatedAt which defaults to the datetime of creation ("default getdate() in SQL Server).

(The exact syntax varies depending on the databse.)

With the exception of race conditions, I can find the last inserted row by doing "select * from table order by 1 desc".

Although these take extra space, I've found that they more than pay back by being able to resolve issues over time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM