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

Instruction

Perfect! Time to wrap things up. First, a quick review:

  1. To define a primary key when creating a table:
    CREATE TABLE swimming_pool (
      id integer PRIMARY KEY,
      address text
    );
  2. To add a primary key to an existing table:
    ALTER TABLE swimming_pool
    ADD [CONSTRAINT swimming_pool_pk] PRIMARY KEY (id);
  3. To delete a primary key:
    ALTER TABLE swimming_pool
    DROP CONSTRAINT swimming_pool_pkey;
  4. To add a foreign key when creating a table:
    CREATE TABLE player (
      id integer PRIMARY KEY,
      first_name varchar(32),
      last_name varchar(32),
      coach_id integer,
      FOREIGN KEY (coach_id) REFERENCES coach (id)
    );
  5. To add a foreign key to an existing table:
    ALTER TABLE player
    ADD [CONSTRAINT player_fk] FOREIGN KEY (coach_id) REFERENCES coach (id);
  6. To delete a foreign key:
    ALTER TABLE player
    DROP CONSTRAINT player_coach_id_fkey;
  7. We can specify the exact behavior of foreign keys when data changes in the referenced table. The possible options are CASCADE, NO ACTION, SET NULL, SET DEFAULT and RESTRICT (default option).

How about a short quiz now?

Exercise

Click Next exercise to continue.