Mysql can't make column auto_increment
To configure AUTO_INCREMENT
in MySQL, the field must be of integer type and designated as a PRIMARY KEY
. Here's how you create a new table with an auto-incrementing column:
If you're working with an existing table:
This command will make the ID
field increase automatically with each new record.
Laying the groundwork for AUTO_INCREMENT
Before implementing AUTO_INCREMENT
, here's what you need to do:
Cleaning up existing IDs
Positive integers are the way to go. Eliminate any negative or zero value IDs:
Dealing with duplicates
Discard any duplicate, negative or zero value IDs:
Pumping up the AUTO_INCREMENT value
Ensure the AUTO_INCREMENT
value starts above your current maximum ID value:
The quirks of AUTO_INCREMENT
Handle 'NO_AUTO_VALUE_ON_ZERO' mode
When modifying a table using ALTER TABLE
with AUTO_INCREMENT
, use 'NO_AUTO_VALUE_ON_ZERO' to stop 0
from resetting the counter:
Taming SQL_MODE
You may need to adjust SQL_MODE
temporarily - just remember to reset it afterward!
Pro tips for AUTO_INCREMENT
Beware reserved keywords
Avoid using reserved English keywords. Doing so will ensure your code doesn't throw up confetti... er, I mean errors:
Ensure data integrity
Ensure your data integrity is fit as a fiddle before rocking the boat:
Test all changes
After making changes, check that everything is functioning as expected by inserting new data:
Turn error messages into guides
Don't fear error messages - think of them as your spirit guide through the wilderness of SQL troubleshooting.
Was this article helpful?