Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I enforce compound uniqueness in MySQL?

I have run into a situation where I want to ensure that a compound element of a table is unique. For example:

Table (
  id char(36) primary key,
  fieldA varChar(12) not null,
  fieldB varChar(36) not null
)

I don't want fieldA and fieldB to be a compound primary key, since they change frequently, and 'id' is used as a reference throughout the system.

fieldA and fieldB are not unique in and of themselves, but their combinations need to be unique. So for example, {{1, Matt, Jones}, {2, David, Jones}, {3, Matt, Smith}} would be valid data, but {{1, Matt, Jones}, {2, Matt, Jones}} would not be.

like image 356
David Smith Avatar asked Jun 29 '09 16:06

David Smith


People also ask

Can I define multiple unique constraints on a table in MySQL?

A PRIMARY KEY constraint automatically has a UNIQUE constraint. However, you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.

How do I create a unique constraint in MySQL?

The syntax for creating a unique constraint using an ALTER TABLE statement in MySQL is: ALTER TABLE table_name ADD CONSTRAINT constraint_name UNIQUE (column1, column2, ... column_n); table_name.

How do I make unique column combinations in MySQL?

Hence, if you want to have a more than one column or a set of columns with unique values, you cannot use the primary key constraint. Luckily, MySQL provides another kind of index called UNIQUE index that allows you to enforce the uniqueness of values in one or more columns.

Can we have multiple unique keys in a table MySQL?

We can define multiple Unique keys on a table where one or more columns combine to make a Unique key. According to ANSI, we can use multiple NULL values but in the SQL server, we can add only one NULL value.


2 Answers

You can add an UNIQUE key constraint on the two fields:

ALTER TABLE `table_name` ADD UNIQUE (
`fieldA`,
`fieldB`
);
like image 136
Siddhartha Reddy Avatar answered Sep 30 '22 17:09

Siddhartha Reddy


Add a UNIQUE key to your table definition:

Table (
  id char(36) primary key,
  fieldA varChar(12) not null,
  fieldB varChar(36) not null,
  UNIQUE fieldA_fieldB (fieldA, fieldB)
)
like image 37
gahooa Avatar answered Sep 30 '22 17:09

gahooa