Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I specify unique constraint for multiple columns in MySQL?

I have a table:

table votes (     id,     user,     email,     address,     primary key(id), ); 

Now I want to make the columns user, email, address unique (together).

How do I do this in MySql?

Of course the example is just... an example. So please don't worry about the semantics.

like image 562
Niyaz Avatar asked Mar 11 '09 19:03

Niyaz


People also ask

How do I create a unique constraint in multiple columns?

To define a UNIQUE constraint, you use the UNIQUE keyword followed by one or more columns. You can define a UNIQUE constraint at the column or the table level. Only at the table level, you can define a UNIQUE constraint across multiple columns.

Can unique key have multiple columns?

A unique key is a set of one or more than one fields/columns of a table that uniquely identify a record in a database table. You can say that it is little like primary key but it can accept only one null value and it cannot have duplicate values.

How do I create a unique constraint on multiple columns in SQL Server?

SQL UNIQUE constraint for 2 columns example Notice that we named the UNIQUE constraints using CONSTRAINT keyword. We can use this name to remove the UNIQUE constraint later if we want. To define a UNIQUE on multiple columns, we put a comma-separated columns list inside parenthesis that follows the UNIQUE keyword.

Can I define multiple unique key in a MySQL table?

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

I have a MySQL table:

CREATE TABLE `content_html` (   `id` int(11) NOT NULL AUTO_INCREMENT,   `id_box_elements` int(11) DEFAULT NULL,   `id_router` int(11) DEFAULT NULL,   `content` mediumtext COLLATE utf8_czech_ci NOT NULL,   PRIMARY KEY (`id`),   UNIQUE KEY `my_uniq_id` (`id_box_elements`,`id_router`) ); 

and the UNIQUE KEY works just as expected, it allows multiple NULL rows of id_box_elements and id_router.

I am running MySQL 5.1.42, so probably there was some update on the issue discussed above. Fortunately it works and hopefully it will stay that way.

like image 35
Frodik Avatar answered Oct 22 '22 13:10

Frodik


To add a unique constraint, you need to use two components:

ALTER TABLE - to change the table schema and,

ADD UNIQUE - to add the unique constraint.

You then can define your new unique key with the format 'name'('column1', 'column2'...)

So for your particular issue, you could use this command:

ALTER TABLE `votes` ADD UNIQUE `unique_index`(`user`, `email`, `address`); 
like image 174
jonstjohn Avatar answered Oct 22 '22 14:10

jonstjohn