How does MySQL Auto Increment work?

When adding to the database programatically, do I just add a number, and then the database automatically increments that number?

Yes, that's the way auto_increment works.

  • The value will be incremented for each new row

  • The value is unique, duplicates are not possible

  • If a row is deleted, the auto_increment column of that row will not be re-assigned.

  • The auto_increment value of the last inserted row can be accessed using the mySQL function LAST_INSERT_ID() but it must be called right after the insert query, in the same database connection

mySQL Reference


1 more, You can insert your own value also (ie your random value).


Yes. Auto_Increment columns work like they say on the tin. Tips

  • when INSERT - ing, use NULL or omit the column

  • Use LAST_INSERT_ID() (or API equivalents) to obtain the last generated value.

  • for security and business logic reasons, it's usually better form to not directly use a key value for a customer identifier. Consider using Hashed / randomised surrogate customer keys instead.

Ta


When you enable Auto Increment an ID will always get automatically added whenever a new record is made.. Example:

If you have 1 record with ID 1 in your table and you add a new record, the ID will automatically be 2.