MySQL Composite Primary Key Guide

In MySQL, you can define a composite primary key by using the PRIMARY KEY keyword in the CREATE TABLE statement. Here is an example:

CREATE TABLE my_table (
    column1 INT,
    column2 INT,
    column3 VARCHAR(50),
    PRIMARY KEY (column1, column2)
);

In this example, the table ‘my_table’ has three fields: column1, column2, and column3. By using the PRIMARY KEY keyword, we define column1 and column2 as a multi-field composite primary key. This means that any record inserted into the table must have a unique combination of values, not just values for individual fields.

It is important to note that MySQL does not allow the definition of two identical multi-column composite primary keys. Therefore, if you try to define a new multi-column composite primary key in a table that already has a primary key, you may encounter an error.

bannerAds