Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
Defining columns with UNIQUE
Adding and removing UNIQUE constraints
Summary

Instruction

Good! As you can see, UNIQUE with multiple columns works exactly as PRIMARY KEY does.

There is, however, one major difference between the two. We can only have one primary key in a given table, but we can have as many UNIQUE constraints as we want. For example:

CREATE TABLE board_game (
  id integer GENERATED ALWAYS AS IDENTITY UNIQUE,
  name varchar(32),
  genre varchar(32),
  studio varchar(32),
  min_players integer,
  min_age integer,
  price decimal(5, 2),
  UNIQUE (name, genre),
  UNIQUE (name, studio)
);

We now have one row with a UNIQUE constraint and a pair of separate UNIQUE constraints, each containing two columns. The database will check to see that each name-genre and name-studio pair are unique. It will also separately ensure that each id is unique.

Is there a difference between one UNIQUE constraint with multiple columns and separate UNIQUE constraints for each column? There is. A UNIQUE constraint with multiple columns means that the column values in the constraint must form a unique group. For example, if you had UNIQUE (name, studio, genre), each name-studio-genre combination must be unique. However, the individual column values could be duplicates, just as we discussed earlier.

On the other hand, if you wrote name ... UNIQUE, studio ... UNIQUE, genre ... UNIQUE, each fo these three column values would have to be unique. Of course, each combination of those values would also be unique, but the database wouldn't check for that.

Exercise

We modified our table so that there are now two UNIQUE constraints. Try to test the table as we did previously: add rows with the same and different values and see what is allowed.