MySQL Primary Key Creation Methods
There are several methods to create a primary key in MySQL.
- Specify the primary key constraint when creating a table.
CREATE TABLE table_name (
id INT PRIMARY KEY,
column1 datatype,
column2 datatype,
...
);
- Add a primary key constraint to an existing table using the ALTER TABLE statement.
ALTER TABLE table_name
ADD PRIMARY KEY (id);
- Use auto-increment primary key when creating a table.
CREATE TABLE table_name (
id INT AUTO_INCREMENT PRIMARY KEY,
column1 datatype,
column2 datatype,
...
);
- Create a primary key using the UNIQUE constraint.
CREATE TABLE table_name (
id INT,
column1 datatype,
column2 datatype,
...
PRIMARY KEY (id)
);
- Create a primary key index using the CREATE INDEX statement.
CREATE TABLE table_name (
id INT,
column1 datatype,
column2 datatype,
...
);
CREATE UNIQUE INDEX index_name
ON table_name (id);
There are common methods for creating a primary key in MySQL, and the specific method chosen will depend on the specific requirements and data table structure.