MySQL Unique Key Pairs

This is one of those things that is easy to do, but I frequently forget because of how little I deal with SQL syntax. Essentially, there are times when you want two fields to be unique together. For example, you might have a table with a city field and a state field. It's okay to have an entry for Portland, Oregon and an entry for Portland, Maine, but it is not okay to have Portland, Oregon more than once in the table. This is when you need a unique key pair (or it could be any number of keys that are unique together).

First, we create an overly simple example table:

MySQL:
  1. CREATE TABLE `test`.`exampletable` (
  2.     `value1` INT UNSIGNED NOT NULL ,
  3.     `value2` INT UNSIGNED NOT NULL ,
  4.     UNIQUE KEY `value1` (`value1`, `value2`)
  5. ) ENGINE = MYISAM ;

Then we plug in some basic values:

MySQL:
  1. INSERT INTO `test`.`exampletable` (
  2. `value1` ,
  3. `value2`
  4. )
  5. VALUES (
  6. '1', '1'
  7. ), (
  8. '1', '2'
  9. ), (
  10. '2', '1'
  11. ), (
  12. '2', '2'
  13. );

That should show you something like 4 row(s) inserted. ( Query took 0.0005 sec ). Now you have 1,1; 1,2; 2,1; and 2,2 stored in the table. What happens when you insert 1,1 again?

MySQL:
  1. INSERT INTO `test`.`exampletable` (
  2. `value1` ,
  3. `value2`
  4. )
  5. VALUES (
  6. '1', '1'
  7. );

You should see this error message: Duplicate entry '1-1' for key 1. Yup, that's all there is to creating unique key pairs in MySQL.


2 Responses to “MySQL Unique Key Pairs”

  1. 1 Renan

    Thanks, really helped me :)

  2. 2 nick

    was looking for this FOREVER!

    i wonder why this was so difficult to find.

    needed 2 columns UNIQUE together and got EXACTLY WHAT I WANT. works like a charm.

    thanks

Leave a Reply