Spiga

MYSQL: make a combination of 2 columns unique

by Gabi Solomon

Here is a recently situation i came across, what if you have a table and you want to make a combination of 2 columns unique. The columns Individually are not unique, but combination is.

To alter 1 column to a unique key you would use :

SQL:
  1. ALTER TABLE user MODIFY COLUMN id INT NOT NULL UNIQUE;

Well for a combination of 2 or more columns to be unique you would use:

SQL:
  1. ALTER TABLE user ADD UNIQUE (id,domain);

Hope this helps you.
Cheers

Related Posts

  • Rajesh Katragadda

    Its Wrong.

  • http://www.gsdesign.ro/ Gabi Solomon

    can you tell me why ?

  • http://www.cuhk.edu.hk/chorus Quofei

    I have tried the above SQL command and it works. Thanks

  • http://garlix.com/ Daniel

    It does work. I am surprised that it's that easy! I was looking for how to do this and expected a more complicated solution.

  • ramigb

    thank you, great post it helped me a lot.