Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
Primary keys
4. Adding primary keys to existing tables
Foreign keys
Updating and deleting with foreign keys
Summary

Instruction

Good job! Now, suppose we have a table like this:

CREATE TABLE tennis_court (
  id integer,
  address text,
  type varchar(32)
);

We'd like to add a primary key to the table. How can we do that? It's actually pretty simple:

ALTER TABLE tennis_court
ADD PRIMARY KEY (id);

After invoking this instruction, the id column will be treated as the primary key. However, keep in mind that each of the existing values in the column we want to mark as the primary key must be unique. Otherwise, we won't be able to add the primary key.

Adding a primary key to an existing table can be very useful when we need to change the table's definition without completely removing that table. This option is also frequently used by database modelling tools that auto-generate SQL scripts.

Exercise

The company has created the following table:

CREATE TABLE project (
  id integer,
  name varchar(64),
  description text,
  manager_id integer
);

They now need you to add a primary key to the id column.