Okay, time to move on. Do you remember that we can include more than one column in the PRIMARY KEY
? The same rule applies to the UNIQUE
constraint. Take a look:
CREATE TABLE board_game (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name varchar(32),
genre varchar(32),
min_players int,
min_age int,
price decimal(5, 2),
UNIQUE (name, genre)
);
At the end of the instruction, we put the keyword UNIQUE
and within parentheses we provided the column pair that must be unique.
From now on, each pair of name and genre values must be unique for each row. The individual column values, however, may be duplicated as long as the name-genre pair is unique. So, both (name='ABC'
, genre='horror'
) and (name='ABC'
, genre='fantasy'
) will be accepted, just as in the case of PRIMARY KEY
s on multiple columns.
In other words, no two games of the same genre can have the same name, but if the genres are different, then identical names are allowed (and vice versa).