AUTO INCREMENT Primary Key in MySQL

Create an AUTO INCREMENT Primary Key in MySQL

To create an auto increment primary key in mysql we have 2 ways.

1 On Create Table

Method 1

CREATE TABLE table_name
(
    id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(255)
)

Method 2

CREATE TABLE table_name
(
    id INT NOT NULL AUTO_INCREMENT,
    name VARCHAR(255),
    PRIMARY KEY(id)
)

Method 3: Adding a name to the constraint

CREATE TABLE table_name
(
    id INT NOT NULL AUTO_INCREMENT,
    name VARCHAR(255),
    CONSTRAINT PK_table_name PRIMARY KEY(id)
)

2 On ALTER Table

ALTER TABLE table_name ADD PRIMARY KEY(id);
/*FOR AUTO INCREMENT*/
ALTER TABLE table_name MODIFY id INT AUTO_INCREMENT