This tutorial explains how to create sequences using the AUTO_INCREMENT attribute in MySQL with syntax and examples.
In MySQL, you can create a column that contains a sequence of numbers (1, 2, 3, and so on) by using the AUTO_INCREMENT attribute. The AUTO_INCREMENT attribute is used when you need to create a unique number to act as a primary key in a table.
The syntax to create a sequence (or use the AUTO_INCREMENT attribute) in MySQL is:
The attribute to use when you want MySQL to assign a sequence of numbers automatically to a field (in essence, creating an autonumber field).
Each column should be defined as NULL or NOT NULL. If this parameter is omitted, the database assumes NULL as the default.
Let's look at an example of how to use a sequence or the AUTO_INCREMENT attribute in MySQL.
For example:
This MySQL AUTO_INCREMENT example creates a table called contacts which has 4 columns and one primary key:
Now that you've created a table using the AUTO_INCREMENT attribute, how can you change the starting value for the AUTO_INCREMENT field if you don't want to start at 1?
You can use the ALTER TABLE statement to change or set the next value assigned by the AUTO_INCREMENT.
In MySQL, the syntax to change the starting value for an AUTO_INCREMENT column using the ALTER TABLE statement is:
The name of the table whose AUTO_INCREMENT value you wish to change. Since a table in MySQL can only contain one AUTO_INCREMENT column, you are only required to specify the table name that contains the sequence. You do not need to specify the name of the column that contains the AUTO_INCREMENT value.
The next value in the sequence to assign in the AUTO_INCREMENT column.
Let's look at an example of how to change the starting value for the AUTO_INCREMENT column in a table in MySQL.
For example:
This MySQL AUTO_INCREMENT example would change the next value in the AUTO_INCREMENT field (ie: next value in the sequence) to 50 for the contact_id field in the contacts table.
Here are some other tutorials to help you learn more about sequences in MySQL: