Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Even if you can query the next available primary key value, it wouldn't help you. Unless you lock the table, you can't use that value before some other database client might grab it for their insert.</p> <p>Instead, you should just insert your row, and then you can query the <em>most recent</em> key value generated during your current session. Every database that supports auto-generated primary keys provides a method to retrieve the most recent key inserted during your session.</p> <p>The "during your session" part is important because it shields your session from any inserts being done concurrently by other clients. They can generate key values and your session will continue to report the same value <em>it</em> inserted most recently.</p> <p>@Stuart Childs <a href="https://stackoverflow.com/questions/579957/model-next-available-primary-key/580061#580061">supposes</a> that MySQL generates the next ID with <code>MAX(column_name)+1</code> but this is incorrect. Say you insert a row and an ID value is generated. But you rollback this insert, or subsequently <code>DELETE</code> that row. The next time you insert, MySQL will generate a brand new ID value. So the ID value is one greater than the last ID value generated <em>by any client</em>, regardless of what rows are currently stored in the table.</p> <p>Likewise if you insert but don't commit immediately. Before you commit, some other client does an insert. Both your session and the other client's session will have their own unique ID value generated. Auto-generated primary keys operate without regard to transaction isolation, to ensure uniqueness.</p> <p>Auto-generated primary key values are not re-used or allocated to more than one session, even if you have not yet committed your insert, or if you rollback the insert, or if you delete the row.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload