Friday 2 November 2018

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.

 Answers


ALTER TABLE `votes` ADD UNIQUE `unique_index`(`user`, `email`, `address`);



Multi column unique indexes do not work in MySQL if you have a NULL value in row as MySQL treats NULL as a unique value and at least currently has no logic to work around it in multi-column indexes. Yes the behavior is insane, because it limits a lot of legitimate applications of multi-column indexes, but it is what it is... As of yet, it is a bug that has been stamped with "will not fix" on the MySQL bug-track...



This works for mysql version 5.5.32
ALTER TABLE  `tablename` ADD UNIQUE (`column1` ,`column2`);



MySql 5 or higher behaves like this (I've just tested):
  • you can define unique constraints involving nullable columns. Say you define a constraint unique (A, B) where A is not nullable but B is
  • when evaluating such a constraint you can have (A, null) as many times you want (same A value!)
  • you can only have one (A, not null B) pair
Example: PRODUCT_NAME, PRODUCT_VERSION 'glass', null 'glass', null 'wine', 1
Now if you try to insert ('wine' 1) again it will report a constraint violation Hope this helps



For adding unique index following are required:
1) table_name
2) index_name
3) columns on which you want to add index
ALTER TABLE  `tablename` 
ADD UNIQUE index-name
(`column1` ,`column2`,`column3`,...,`columnN`);
In your case we can create unique index as follows:
ALTER TABLE `votes`ADD 
UNIQUE <votesuniqueindex>;(`user` ,`email`,`address`);

0 comments:

Post a Comment