Skip to content
Hands-on Mentor
ENTR
Back to blog

Primary key vs foreign key: what each one does, with SQL examples

A primary key identifies each row in a table. A foreign key links a row to another table. See both in SQL, with the errors they prevent and a few examples.

4 min read

The difference between a primary key and a foreign key is simple. A primary key (PRIMARY KEY) identifies each row in its own table, so it must be unique and cannot be empty. A foreign key (FOREIGN KEY) is a column that points to the primary key of another table, which links the two tables. Together they keep a database consistent.

The error messages below come from running the code in PostgreSQL. Real PostgreSQL adds extra detail lines to some of them.

What is a primary key? Examples

A student list can contain two people with the same name, so a name cannot identify a row. Each row gets a unique id:

CREATE TABLE department (
  id INTEGER PRIMARY KEY,
  name VARCHAR(40) NOT NULL
);

INSERT INTO department VALUES
  (1, 'Computer Programming'),
  (2, 'Business Administration'),
  (3, 'Psychology');

If you try to add the same id twice:

INSERT INTO department VALUES (1, 'Law');
Outputduplicate key value violates unique constraint "department_pkey"

A primary key has two rules:

  • Unique: no two rows can have the same value.
  • Not empty: it never accepts NULL. Trying to insert a row with a NULL id fails with null value in column "id" of relation "department" violates not-null constraint.

What is a foreign key?

Instead of repeating the department name on every student row, store only the department's id:

CREATE TABLE student (
  id INTEGER PRIMARY KEY,
  name VARCHAR(30) NOT NULL,
  department_id INTEGER REFERENCES department(id)
);

INSERT INTO student VALUES (1, 'Maya', 1), (2, 'Elena', 2);

REFERENCES department(id) means that department_id can only hold an id that really exists in the department table.

A foreign key stops two kinds of mistakes.

1. Pointing to something that does not exist:

INSERT INTO student VALUES (3, 'Noah', 9);

There is no department 9, so PostgreSQL rejects the row:

Outputinsert or update on table "student" violates foreign key constraint "student_department_id_fkey"

Without the foreign key, Noah would belong to a "ghost" department and would never show up in a report by department.

2. Deleting something that is still in use:

DELETE FROM department WHERE id = 2;

Elena is still in Business Administration, so PostgreSQL refuses:

Outputupdate or delete on table "department" violates foreign key constraint "student_department_id_fkey" on table "student"

First move or delete Elena, then delete the department.

What happens on delete? ON DELETE options

Sometimes you want the linked rows to disappear too. Here, deleting a student also deletes the student's course registrations:

CREATE TABLE registration (
  student_id INTEGER REFERENCES student(id) ON DELETE CASCADE,
  course VARCHAR(30),
  PRIMARY KEY (student_id, course)
);

INSERT INTO registration VALUES
  (1, 'Databases I'),
  (1, 'Web Programming'),
  (2, 'Accounting I');

DELETE FROM student WHERE id = 1;

SELECT * FROM registration;
student_idcourse
2Accounting I

Both of Maya's registrations were removed with her. Only Elena's row is left.

OptionWhen the parent row is deleted
(default)The delete is rejected
ON DELETE CASCADELinked rows are deleted too
ON DELETE SET NULLThe foreign key column becomes NULL

CASCADE is powerful. One delete can remove hundreds of linked rows without you noticing.

Can a table have two primary keys?

No. A table has exactly one primary key. PostgreSQL rejects a second one:

CREATE TABLE bad_table (a INTEGER PRIMARY KEY, b INTEGER PRIMARY KEY);
Outputmultiple primary keys for table "bad_table" are not allowed

What a table can have is one primary key made of several columns. In registration, one column is not enough: a student takes many courses and a course has many students. The pair is unique, so the key is PRIMARY KEY (student_id, course). Registering the same student for the same course twice fails with duplicate key value violates unique constraint "registration_pkey".

If you need a second column to be unique, use UNIQUE. It also rejects duplicates, for example email VARCHAR(50) UNIQUE.

Natural key or surrogate key?

  • Natural key: a real-world value that is already unique, such as an email address or a student number.
  • Surrogate key: a meaningless number that the database generates (id).

Natural keys can change over time (people change email addresses) or turn out not to be as unique as you thought. Most designs use a surrogate id as the primary key and add a UNIQUE constraint to the natural value.

Summary

Primary keyForeign key
JobIdentifies the rowLinks to another table
Unique?YesNo (many students share a department)
Can be NULL?NoYes, unless you forbid it
PreventsDuplicate rowsGhost references and orphan rows

What to read next

  • [Foreign keys](/learn/sql/foreign-key): build the Northbridge University tables with these rules.
  • [Database normalization explained](/blog/database-normalization): how to decide which tables you need.
  • [SQL for beginners: the full course](/courses/sql)
  • #sql
  • #primary key
  • #foreign key
  • #database design
All posts