Jump to content

If the PK of a table is set to auto increment, can I trust the highest ID...


DWilliams

Recommended Posts

...to be the latest entry?

 

If I want to get the ID of the last inserted row, can I just order by the PK and limit 1? I know about mysql_insert_id() and similar functions, but I need to do this from a separate script execution and those must be run directly after the insert.

Link to comment
Share on other sites

You cannot guarantee that the highest id will be the id that any invocation of a script just inserted because concurrent visitors can each cause their own id to be inserted. You will end up cross-linking information using the wrong id.

 

How are you 'executing' these separate scripts that need to use the correct id and why don't you have all the related processing on one page?

Link to comment
Share on other sites

You cannot guarantee that the highest id will be the id that any invocation of a script just inserted because concurrent visitors can each cause their own id to be inserted. You will end up cross-linking information using the wrong id.

 

How are you 'executing' these separate scripts that need to use the correct id and why don't you have all the related processing on one page?

 

I see what you're saying but luckily in my case, the script that does the inserting is executed by cron and not by visitors. In that case, it should be fine, right? The script will only run every 30 minutes or so.

 

The script in question is connecting to a third party API and processing all new entries that have been added since the last script execution. Each remote entry has an ID, so I store IDs that have already been processed to ensure that they don't get processed again. Ideally my script will keep parsing new entries until it hits one with an ID equal to the most recently inserted ID in my database.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.