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
10. Adding a UNIQUE constraint
Summary

Instruction

Very well done! We know how to add UNIQUE constraints when we define a table. How do we add a UNIQUE constraint to an existing table? Let's say we have the following table:

CREATE TABLE video_game (
  id integer PRIMARY KEY,
  name varchar(64),
  platform varchar(64),
  price decimal(6, 2)
);

We'd like to add a UNIQUE constraint to a group of two columns: name and platform. Take a look:

ALTER TABLE video_game
ADD UNIQUE (name, platform);

The query above will add a UNIQUE constraint to our table. However, keep in mind that all existing name-platform combinations must be unique. If that's not the case, we won't be able to add the constraint. What's more, once we do add it, each new name-platform combination must be unique as well.

Exercise

We've got a table named card_game that's defined like this:

CREATE TABLE card_game (
  id integer PRIMARY KEY,
  name varchar(64) UNIQUE,
  rank integer
);

Your task is to add a UNIQUE constraint to the rank column.