Multi-Column Primary Key in MySQL 5

Quoted from the CREATE TABLE Syntax page:

A PRIMARY KEY can be a multiple-column index. However, you cannot create a multiple-column index using the PRIMARY KEY key attribute in a column specification. Doing so only marks that single column as primary. You must use a separate PRIMARY KEY(index_col_name, ...) clause.

Something like this can be used for multi-column primary keys:

CREATE TABLE
    product (
        category INT NOT NULL,
        id INT NOT NULL,
        price DECIMAL,
        PRIMARY KEY(category, id)
    );

From 13.1.20.6 FOREIGN KEY Constraints


The primary key is a unique value for the row. It makes no sense to include price, a value that could change. Imagine if you had to change a large range of prices, then all those primary key values would change. What a mess that would be!


Primary key is a domain concept that uniquely (necessarily and sufficiently) identifies your entity among similar entities. A composite (multiple-column) primary key makes sense only when a part of the key refers to a particular instance of another domain entity.

Let's say you have a personal collection of books. As long as you are alone, you can count them and assign each a number. The number is the primary key of the domain of your library.

Now you want to merge your library with that of your neighbor but still be able to distinguish to whom a book belongs. The domain is now broader and the primary key is now (owner, book_id).

Thus, making each primary key composite should not be your strategy, but rather you should use it when required.

Now some facts about MySQL. If you define a composite primary key and want the RDBSM to autoincrement the ids for you, you should know about the difference between MyISAM and InnoDB behavior.

Let's say we want a table with two fields: parent_id, child_id. And we want the child_id to be autoincremented.

MyISAM will autoincrement uniquely within records with the same parent_id and InnoDB will autoincrement uniquely within the whole table.

In MyISAM you should define the primary key as (parent_id, child_id), and in InnoDB as (child_id, parent_id), because the autoincremented field should be the leftmost constituent in the primary key in InnoDB.