9

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.

2 Answers 2

12

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)

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.