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.

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?

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.