Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
Foreign keys
Multi-column Foreign Keys
Summary
18. Question 1

Instruction

That's it! You've mastered everything we've prepared for you so far.

Let's summarize what we learned in this part:

  1. A foreign key is a link between two tables. It ensures that a column in table A (which is marked as a foreign key) references a correct value in a column in table B. Here is an example of a foreign key:
    CREATE TABLE position (
      id integer PRIMARY KEY,
      title varchar(255) NOT NULL,
      department_id integer NOT NULL,
      FOREIGN KEY (department_id)
        REFERENCES department (id)
    );
  2. A foreign key may consist of multiple columns:
    CREATE TABLE department (
      id integer PRIMARY KEY,
      office_floor integer NOT NULL,
      office_building_name varchar(255) NOT NULL,
      FOREIGN KEY (office_floor, office_building_name)
        REFERENCES office (floor, building_name)
    );
  3. You can have more than one foreign key in a single table.

Now, how about a few quick exercises before we let you go?

Exercise

At the university, there are courses and lecturers. Each course is led by a specific lecturer.

Create a course table with the following columns:

  1. id – integer, primary key.
  2. title – up to 64 characters.
  3. lecturer_id – integer, foreign key referring to id column from the lecturer table.