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

Instruction

Perfect! When we add a primary key to a table, the database engine internally stores the primary key in a constraint object. By default, this object gets an auto-generated name, which we'll explain in a second. However, you can also specify your own name for a constraint. For instance, we have the following table:

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

We can add a primary key with a custom name in the following way:

ALTER TABLE tennis_court
ADD CONSTRAINT court_pk PRIMARY KEY (id);

The code above will add a primary key constraint with the custom name court_pk.

Exercise

Let's try to add the primary key to the project table again:

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

Add a primary key constraint on the id column and give the constraint the name project_pk.