By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

Adding unique index on multiple columns in MySQL

How to add a composite unique constraint in MySQL, also known as adding a multi-column index.

Edited: 2014-12-28 01:16

Adding a unique index on multiple columns in MySQL, can make it easier to avoid duplicated content in a MySQL table.

One advantage of doing this, is that it works with the ON DUPLICATE KAY syntax, which will make it easier to query the database.

You can add a unique index with the ALTER TABLE command, like shown in the below example:

ALTER TABLE table_name ADD UNIQUE unique_index(column_1, column_2);

You can easily make it cover more columns by extending it with more commas, which can be done like:

ALTER TABLE table_name ADD UNIQUE unique_index(column_1, column_2, column_3);