Even if you can request the next available primary key value, this will not help you. If you do not lock the table, you cannot use this value before any other database client can capture it for its insertion.
Instead, you just need to insert your row, and then you can request the most recent key value generated during the current session. Each database that supports automatically generated primary keys provides a method for retrieving the most recent key inserted during a session.
The in-session part is important because it protects your session from any insertions performed by other clients at the same time. They can generate key values, and your session will continue to report the same value that it inserted recently.
@Stuart Childs assumes MySQL generates the following identifier with MAX(column_name)+1 , but this is not true. Let's say you insert a row and generate an ID value. But you roll back this insert, and then DELETE this line. The next time you insert, MySQL will generate a new ID value. Thus, the ID value is greater than the last identifier value generated by any client, regardless of which rows are currently stored in the table.
Similarly, if you insert, but do not commit immediately. Before committing, any other client makes an insert. Both your session and another client session will have their own unique identifier value. Automatically generated primary keys work independently of transaction isolation to ensure uniqueness.
Automatically generated primary key values ββare not reused or assigned to more than one session, even if you have not done your insertion yet, or if you canceled the insertion or deleted the row.
Bill karwin
source share