Multiple fields Primary Key in MySQL

Create a Multiple fields Primary Key in MySQL

To create a multi primary key that contains multiple columns in mysql we have 2 ways.

1 On Create Table

Method 1

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

Method 2

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

Method 3: Adding a name to the constraint

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

2 On ALTER Table

ALTER TABLE table_name ADD PRIMARY KEY(id, name);