AUTO INCREMENT Columns in MySQL
In MySQL, to create a column that is both AUTO_INCREMENT
a PRIMARY KEY
, you typically use it with integer types such as INT
or BIGINT
. The AUTO_INCREMENT
attribute automatically generates a unique value for each new record, incrementing by one (or another specified value). The PRIMARY KEY
constraint uniquely identifies each record in a table.
Here’s how you can create such a column:
1. When Creating a New Table:
CREATE TABLE table_name (
column_name INT NOT NULL AUTO_INCREMENT,
... (other columns) ...
PRIMARY KEY (column_name)
);
Example:
If you’re creating a table named students
and you want an id
column that auto-increments and is the primary key:
CREATE TABLE students (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(255),
age INT,
PRIMARY KEY (id)
);
2. Modifying an Existing Table:
You can use the statement if you have an existing table and want to add a new
primary key column. However, be cautious when altering existing tables, especially if they contain data.
ALTER TABLE table_name
ADD column_name INT NOT NULL AUTO_INCREMENT PRIMARY KEY;
Example:
Adding an id
column to an existing students
Table:
ALTER TABLE students
ADD id INT NOT NULL AUTO_INCREMENT PRIMARY KEY;
Note:
- A table can have only one
AUTO_INCREMENT
column. - The
AUTO_INCREMENT
column must be defined as a key (either primary or unique). - If the table already has data and you’re adding a new
AUTO_INCREMENT
primary key column, MySQL will automatically populate the new column with sequential numbers for existing rows.