AUTO_INCREMENT for PRIMARY KEY

We can add a new column like an id, that auto increments itself for every row that is inserted to the table.

In this MySQL Tutorial, we shall create a new column that is PRIMARY KEY with AUTO_INCREMENT column modifier.

To add a new column to MySQL, following is the syntax of the SQL Query:

</>
Copy
ALTER TABLE table_name
ADD [COLUMN] new_column_name AUTO_INCREMENT PRIMARY KEY;

Example 1 – AUTO_INCREMENT for PRIMARY KEY

For this example, let us consider the following table, students.

MySQL add new column that auto increments

Run the following SQL Query to add a new column named id that acts as PRIMARY KEY and auto increments for each insert.

</>
Copy
 ALTER TABLE students
 ADD id INT AUTO_INCREMENT PRIMARY KEY;
MySQL add integer column that is PRIMARY KEY and auto increments

The column id is added successfully. Lets see the contents of the modified table.

MySQL new column added

Let us see the updated table schema.

Updated table schema when new primary column is added