Alex Rivera | Logout

Accessing last inserted row in MySQL

Asked 2012-09-26T11:18:58.137
13

On my DB server, I am inserting data in a table having an auto increment field say 'id'. Now I want to use the value of this last inserted 'id' in subsequent steps. I can use this:

  select * from table_name order by id desc limit 1; 

But the problem here is, it is a server and many more insertions could be happening and there could be a case where I try to retrieve the data with the query I mentioned and get a different id, i.e. between my insert and select there could be some other insert and I won't get the value I inserted. Any way in which this could be addressed?

Edit
Report

1 Answer

2

you can get the id if you call LAST_INSERT_ID() function immediately after insertion and then you can use it.

answered 2012-10-24T05:51:31.440

Your Answer