Rob Michiels
Rob Michiels

Reputation: 134

SQL multiple unique columns

Is it possible to use unique on multiple columns?

like:

 user_vote user_id 
 ------------------
      1         1
      1         2
      2         1 

both unique

This must be possible

But:

  user_vote user_id
     1         2
     1         2 

This must not be possible

Upvotes: 1

Views: 88

Answers (3)

Rajib Ghosh
Rajib Ghosh

Reputation: 640

MySQL / SQL Server / Oracle / MS Access:

 CREATE TABLE uservotetable
 (
   user_vote int NOT NULL,
   user_id int NOT NULL,
 CONSTRAINT uservote UNIQUE (user_vote ,user_id)
  );

and if you created your table before ..then you can use ALTER

  ALTER TABLE uservotetable
  ADD CONSTRAINT uservote UNIQUE (user_vote ,user_id)

this can be useful for you sql_unique

Upvotes: 2

hashbrown
hashbrown

Reputation: 3516

You need to define a composite unique constraint.

SQL Server, One way to do that in SQL Server is by adding UNIQUE INDEX

ALTER TABLE table_name ADD UNIQUE INDEX (User_Vote, User_Id);

In Oracle,

ALTER TABLE table_name
ADD CONSTRAINT uc_1 UNIQUE (User_Vote, User_Id)

Upvotes: 1

Mureinik
Mureinik

Reputation: 311073

You can add a unique constraint on the column's combination:

ALTER TABLE my_table
ADD CONSTRAINT my_table_uq UNIQUE (user_vote, user_id)

Upvotes: 2

Related Questions