6

I know that i can make two columns unique keys, but that's not exactly what i want.

I want that for example if col1='1', col2='2' then there can't be another row with col1='1', col2='2', but totally possible to do the following:

+--------+--------+
|  col1  |  col2  |
+--------+--------+
|    1   |    1   |
|    1   |    2   |
|    2   |    1   |
|    2   |    2   |
+--------+--------+

while this is impossible:

+--------+--------+
|  col1  |  col2  |
+--------+--------+
|    1   |    1   |
|    1   |    1   |
+--------+--------+

Making both unique keys is not an option as in col1='1', col2='1' and col1='1', col2='2' col1 is the same and that's not allowed if both are unique keys.

GDavid
  • 128
  • 1
  • 2
  • 12

2 Answers2

13

You need composite unique index.

ALTER TABLE tablename ADD UNIQUE KEY `uidx` (`col1`, `col2`);
Samir Selia
  • 7,007
  • 2
  • 11
  • 30
5

You just need to declare a unique index between the two columns col1, and col2:

CREATE TABLE Table1
(
  `col1` int, 
  `col2` int,
   UNIQUE `unique_index`(`col1`, `col2`)
);

If you try to insert 1, 1, into col1 and col2, you will get the following error:

Duplicate entry '1-1' for key 'unique_index'

You can try it yourself here.

Samir Selia
  • 7,007
  • 2
  • 11
  • 30