I have 3 options of adding a new UNIQUE id (primary_key) to one of my particular tables.
- Create AUTO_INCREMENT field.
- SELECT id FROM table ORDER BY id DESC LIMIT 1
- SELECT MAX(id) FROM table
I’m currently using option 2, as people might delete rows from the table they access, so id’s get freed, otherwise i’d be using option 1
What do you reccommend ?
You should always use option 1 (in order to avoid the race hazard of two simultaneous inserting clients reading the current maximum
idbefore either has completed their insertion).AUTO_INCREMENTprevents this hazard from occurring through the use of locks that make the read & write operations atomic.