…
…
SQL and Database Fundamentals · Lesson 30 / 41 · Creating tables and constraints
PreviewIn this lesson you will
You can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
You are building a separate table for the events that student clubs organize, and every event must belong to a club that really exists. An event for a club that does not exist must never be entered. You also need to decide now what happens to a club's events when that club shuts down.
In lesson 14 you met the foreign key as a column that points to the primary key of another table: student.department_id pointed to a department's id, and student.advisor_id pointed to an instructor's id. Since lesson 15 you have followed these links in JOIN conditions. In those lessons the link lived only in the query: when you wrote ON d.id = s.department_id, the two tables matched. In this lesson you will write the same link into the table as a rule. Once the rule exists, the database protects the link itself: it refuses a wrong number and never deletes a linked row without telling you.
In lessons 28 and 29 you built the club table and gave it rules. Now a second table arrives: event. A club organizes many events, and each event has exactly one club. In this one-to-many relationship, the foreign key goes on the "many" side, in the event table.
In this lesson you will:
REFERENCES and explain why a key that does not exist is rejected.To make a column a foreign key, add REFERENCES table(column) to the end of its definition. It reads almost like English: "club_id references the id column of the club table."
OutputCREATE TABLE club (
id INTEGER PRIMARY KEY,
name VARCHAR(60) NOT NULL
);
CREATE TABLE event (
id INTEGER PRIMARY KEY,
club_id INTEGER NOT NULL REFERENCES club(id),
title VARCHAR(100) NOT NULL
);Here club is the parent table and event is the child table. The club_id column in the child table can now hold only an id that really exists in the club table. You can also write the same rule after the column definitions, at table level: FOREIGN KEY (club_id) REFERENCES club(id). Both forms give the same result. The table-level form is required when you reference a two-column (composite) key; for a single column, which one you use is a matter of habit. PostgreSQL gives the constraint a name of its own: event_club_id_fkey (table, column, and "foreign key" abbreviated). You will see this name in error messages in a moment.
This rule has one more consequence: you cannot create a child without its parent. The club table must be created first, then event, and rows must also be added to the club first, then to the event. Put the commands below in an order that first creates the two tables and then fills them.
First create the two tables, then fill both. Put the commands in an order that runs without errors.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
What a foreign key protects is called referential integrity: every filled foreign key value in the child table points to a row that really exists in the parent table. The case database has been built with this rule from the start. The university has 8 departments, numbered 1 through 8. Let's try to add a student to department 99.
Example 1 (case): A student in a department that does not exist
INSERT INTO student (student_no, first_name, last_name, department_id, year, enrollment_date) VALUES ('202699001', 'Test', 'Student', 99, 1, DATE '2026-09-21');
OutputERROR: insert or update on table "student" violates foreign key constraint "student_department_id_fkey"Read the message piece by piece: an insert or update on the student table violates the foreign key constraint named student_department_id_fkey. The constraint name tells you which column caused the problem: department_id. The row never entered the table. The case has 10 foreign keys like this: instructor, student, and course point to department; student points to advisor; course points to its prerequisite course; course offering points to course, term, and instructor; and enrollment points to the offering and the student. We will list them all from the catalog in the "Examples" section below.
The cell below has the same command ready. Run it and see the error. Then change the department number from 99 to 7 and run it again: the row is accepted. Don't worry, the changes in the cell are rolled back after every run, so the case database stays intact. Finally, try changing the department number to NULL and read the constraint name in the error message.
Try it now· not graded; doesn't affect progress
The error in the third attempt does not come from the foreign key. It comes from the NOT NULL rule on the department_id column. This clears up a common misunderstanding: a foreign key column can be left empty. REFERENCES only says "if filled, point to a row that exists"; NOT NULL decides whether it can be empty. In the case, student.department_id has NOT NULL, because every student must have a department. student.advisor_id does not: remember from lesson 7 that 8 students do not have an advisor yet, and their advisor_id is NULL. NULL points to no row, so the foreign key does not check it. In the club example too, if you remove NOT NULL from the club_id column, an event without a club such as (4, NULL, 'Open forum') is accepted. If every event must have a club, you write NOT NULL separately.
A foreign key cannot reference just any column. The referenced column must be the primary key of the parent table or a UNIQUE column. The reason is simple: it must be certain which club an event belongs to. If two clubs could have id 1, which one would club_id = 1 point to? Predict first.
In the club table, id is an ordinary number column, not a primary key. What happens when the second command runs?
CREATE TABLE club (id INTEGER, name VARCHAR(60) NOT NULL); CREATE TABLE event ( id INTEGER PRIMARY KEY, club_id INTEGER REFERENCES club(id) );
The second condition is that the types match. If club.id is an INTEGER and you define event.club_id as VARCHAR(10), PostgreSQL says foreign key constraint "event_club_id_fkey" cannot be implemented: text and numbers cannot be compared. An easy habit is to give the foreign key column the same type as the primary key it references.
The rule works in both directions. Just as you cannot write a key that does not exist into the child table, you cannot delete a row from the parent table while other rows reference it. You will learn the delete command (DELETE) in detail in lesson 36; in this lesson you only run ready-made lines in the form DELETE FROM table WHERE id = 1;. It reads clearly: "delete from the table the row whose id is 1."
Many students think that when a parent is deleted, its children are deleted automatically. Try it in the case:
What happens in the case database if this command runs?
DELETE FROM department WHERE id = 1;
The message names the first obstacle it met: the instructors linked to department 1. They are not the only obstacle; the department's students and courses are there too. Now a subtler case. Department 8, Data Science and Analytics, just opened: it has no students and no courses.
The Data Science and Analytics department (department 8) has 0 students and 0 courses, but 1 instructor (Assistant Professor Yuki Cohen) is linked to it. What happens with DELETE FROM department WHERE id = 8;?
The ON DELETE option that you write at the end of a foreign key decides what happens when a parent is deleted. Let's compare the three main options on the same small data: two clubs (1 Chess, 2 Theater) and three events (1 Tournament and 2 Simul belong to Chess, 3 Showcase belongs to Theater). Every time, DELETE FROM club WHERE id = 1; runs, and the only thing that changes is the end of the foreign key.
Example 2 (our own tables): Deleting a club with CASCADE
CREATE TABLE club (id INTEGER PRIMARY KEY, name VARCHAR(60) NOT NULL); CREATE TABLE event ( id INTEGER PRIMARY KEY, club_id INTEGER REFERENCES club(id) ON DELETE CASCADE, title VARCHAR(100) NOT NULL ); INSERT INTO club VALUES (1, 'Chess'), (2, 'Theater'); INSERT INTO event VALUES (1, 1, 'Tournament'), (2, 1, 'Simul'), (3, 2, 'Showcase'); DELETE FROM club WHERE id = 1; SELECT * FROM event ORDER BY id;
| id | club_id | title |
|---|---|---|
| 3 | 2 | Showcase |
I ran the same code with three different endings. The results side by side:
| End of the foreign key | DELETE FROM club WHERE id = 1; | Left in the event table |
|---|---|---|
| (nothing; the default) | Rejected: violates foreign key constraint "event_club_id_fkey" | All three rows as they were; Chess was not deleted either |
ON DELETE CASCADE | The club is deleted, and so are both of its events | 3 · 2 · Showcase |
ON DELETE SET NULL | The club is deleted, the events stay | 1 · NULL · Tournament, 2 · NULL · Simul, 3 · 2 · Showcase |
The name of the default behavior is NO ACTION; writing RESTRICT gives almost the same result, only the error message has the form violates RESTRICT setting of foreign key constraint. CASCADE means "chain reaction": when the parent goes, the children go too. SET NULL breaks the link: the child stays, but it no longer points to any club.
In the cell below, the setup is ready and the end of the foreign key says CASCADE. Run it and compare with the table above. Then try these in order:
1. Write SET NULL instead of CASCADE and run it. In which rows did club_id become empty?
2. Delete the ON DELETE SET NULL part completely and run it. Which constraint does the error message point to?
3. Put ON DELETE SET NULL back and add NOT NULL where it says club_id INTEGER: club_id INTEGER NOT NULL REFERENCES .... What happened?
Try it now· not graded; doesn't affect progress
In the third attempt the deletion stopped with this error: null value in column "club_id" of relation "event" violates not-null constraint. SET NULL does not work in every situation. During the deletion, PostgreSQL tries to set the children's club_id to NULL, but the column has a NOT NULL rule; the two rules collide, and the whole deletion is rolled back. If you say "when a club closes, let its events stay without a club," the column must accept NULL. When you see SET NULL in a design, check whether the same column also has NOT NULL.
SQL does not tell you which option is right; the rule of the business does. Ask this question: "Does the child row mean anything without its parent?"
| Option | The club's events when the club is deleted | When |
|---|---|---|
NO ACTION (default) / RESTRICT | The deletion is rejected | When linked records must be protected; decide first what to do with them |
CASCADE | They are deleted too | When the child means nothing without its parent (the lines of an order, a club's internal announcements) |
SET NULL | club_id becomes NULL | When the child can live on its own and the column accepts NULL |
SET DEFAULT | It takes the column's default value | Rarely |
What happens to a club's events when the club is asked to be deleted?
For each row, pick its match from the list, then check.
ON DELETE RESTRICTON DELETE CASCADEON DELETE SET NULLCASCADE is powerful but dangerous, because the chain does not stop at one table. Suppose events are linked to clubs and attendance records are linked to events, and both links are built with CASCADE.
Example 3 (our own tables): Chain deletion
CREATE TABLE club (id INTEGER PRIMARY KEY, name VARCHAR(60) NOT NULL); CREATE TABLE event ( id INTEGER PRIMARY KEY, club_id INTEGER NOT NULL REFERENCES club(id) ON DELETE CASCADE, title VARCHAR(100) NOT NULL ); CREATE TABLE attendance ( event_id INTEGER REFERENCES event(id) ON DELETE CASCADE, student_id INTEGER REFERENCES student(id), PRIMARY KEY (event_id, student_id) ); INSERT INTO club VALUES (1, 'Chess'), (2, 'Theater'); INSERT INTO event VALUES (1, 1, 'Tournament'), (2, 1, 'Simul'), (3, 2, 'Showcase'); INSERT INTO attendance VALUES (1, 1), (1, 2), (2, 1), (3, 3), (3, 4); DELETE FROM club WHERE id = 1; SELECT (SELECT (*) club) club, ( (*) event) event, ( (*) attendance) attendance;
| club | event | attendance |
|---|---|---|
| 1 | 1 | 2 |
At first there were 2 clubs, 3 events, and 5 attendance records. You deleted a single row, and 6 rows in total were removed: 1 club, its 2 events, and the 3 attendance records of those events. The DELETE command named only the club table, but rows disappeared from three tables. Before you write CASCADE on a link, follow where the chain reaches.
Think about why this matters in the case. If the links from department to student and from student to enrollment were CASCADE, deleting a department would silently delete all of its students and all of their grade records. This is why the case database uses the default. Now you choose what to do when a department closes:
The university administration is closing a department. The students will be transferred to another department, and the old course records and grades must be kept. Which delete behavior do you choose for the student.department_id foreign key?
Pick an option and see what happens. There are no points; you can try the other options too.
ON DELETE has a sibling, ON UPDATE: it decides what happens to the children when the parent's key changes. It is rarely used because primary key values almost never change; this is one reason to choose artificial numbers (id) that will not change.
Foreign keys are not only rules; they are also documentation. Someone who sees a database for the first time can look at the pg_constraint catalog to see which table is linked to which and what happens on delete; they do not have to guess the JOIN conditions from column names. Schema drawing tools draw their relationship lines from these constraints. In the catalog, foreign keys are the rows with contype = 'f', and the delete behavior is written as one letter in the confdeltype column: a default (reject), r RESTRICT, c CASCADE, n SET NULL.
A foreign key also decides the order of tables and rows. You cannot write a letter to an address before the house is built: if you try to create a table that says REFERENCES club(id) while the club table does not exist, you get the error relation "club" does not exist. Rows follow the same rule: if you add an event linked to club 1 before club 1 is added, you get the error insert or update on table "event" violates foreign key constraint "event_club_id_fkey". When deleting, the order reverses: children first, then the parent. When you write a long setup file, thinking about this order from the start is much easier than debugging later.
The same decisions come up in every application. Let's add playlists to the database of the Earbud music app. A listener has many playlists (playlist.listener_id); a playlist has many songs, and a song can be on many playlists (a playlist_song junction table, like enrollment in lesson 14). The business rules are: if a listener deletes the account, the playlists go too; if a playlist is deleted, the song rows inside it go too; but if a song that sits on a playlist is asked to be deleted, the deletion must be rejected.
Example 4 (outside the case, Earbud): The playlists of a listener whose account is deleted
CREATE TABLE playlist ( id INTEGER PRIMARY KEY, listener_id INTEGER NOT NULL REFERENCES listener(id) ON DELETE CASCADE, name VARCHAR(60) NOT NULL ); CREATE TABLE playlist_song ( playlist_id INTEGER REFERENCES playlist(id) ON DELETE CASCADE, song_id INTEGER REFERENCES song(id), position INTEGER NOT NULL, PRIMARY KEY (playlist_id, song_id) ); INSERT INTO playlist VALUES (1, 19, 'Road trip songs'), (2, 24, 'Quiet evening'); INSERT INTO playlist_song VALUES (1, 23, 1), (1, 27, 2), (2, 27, 1); DELETE FROM listener WHERE id = 19; SELECT * FROM playlist_song ORDER BY playlist_id, position;
| playlist_id | song_id | position |
|---|---|---|
| 2 | 27 | 1 |
When listener 19 (navy_note) was deleted, their playlist 1 went away through CASCADE, and the two song rows of that playlist went away through the second CASCADE. The playlist of listener 24 is still there. Now if you try to delete song 27 (Morning Train) in the same setup, the playlist_song_song_id_fkey constraint rejects the deletion: the song is still on a playlist. You see the same protection in the app's own tables: if you try to delete a song that has been played, for example song 1, Platform Three, you get the error update or delete on table "song" violates foreign key constraint "play_song_id_fkey" on table "play".
In Earbud, if a listener permanently deletes their account, which behavior is best for their likes (the song_like table: who liked which song)?
Let's list the foreign keys in the case, the tables they connect, and their delete behaviors from the catalog. ::regclass converts a table number into a table name.
SELECT conrelid::regclass AS table_name, conname, confrelid::regclass AS target, confdeltype FROM pg_constraint WHERE contype = 'f' ORDER BY conrelid::regclass::text, conname;
| table_name | conname | target | confdeltype |
|---|---|---|---|
| course | course_department_id_fkey | department | a |
| course | course_prerequisite_id_fkey | course | a |
| course_offering | course_offering_course_id_fkey | course | a |
| course_offering | course_offering_instructor_id_fkey |
Adding rows in the wrong order. If you add the event first and the club second, the club does not exist yet when the event row is added:
OutputINSERT INTO event VALUES (1, 1, 'Tournament');
INSERT INTO club VALUES (1, 'Chess');
ERROR: insert or update on table "event" violates foreign key constraint "event_club_id_fkey"The second line never runs, because execution stops at the first line. The fix is not to delete rows or remove the constraint, but to swap their places: parent first, child second. By the same logic, when you create tables you must create the referenced table first; a table that says REFERENCES club(id) stops with the error relation "club" does not exist if the club table is missing.
REFERENCES table(column) turns a foreign key into a rule: only a key that exists in the parent can be written into the child table; NULL is allowed, NOT NULL decides whether it is required; the referenced column must be a primary key or UNIQUE.ON DELETE says what happens when the parent is deleted: the default rejects, CASCADE deletes the children too (along the whole chain), SET NULL breaks the link but the deletion is rejected if the column is NOT NULL; the choice is a business rule.Next lesson: we have built links one by one; next is modeling a whole club system (clubs, events, members, presidents) on paper with entities and relationships.
Exercises and quiz are for members
This lesson has 7 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
| a |
| course_offering | course_offering_term_id_fkey | term | a |
| enrollment | enrollment_offering_id_fkey | course_offering | a |
| enrollment | enrollment_student_id_fkey | student | a |
| instructor | instructor_department_id_fkey | department | a |
| student | student_advisor_id_fkey | instructor | a |
| student | student_department_id_fkey | department | a |
All ten foreign keys are a: in the case, no deletion chains. This does not mean "no row can be deleted"; a row that has no row referencing it (for example, an offering with no enrollments) can be deleted. course_prerequisite_id_fkey also shows that a table can reference itself: the prerequisite course is also in the course table.
The same link can also be written after the column definitions. The result in the catalog is the same.
CREATE TABLE club (id INTEGER PRIMARY KEY, name VARCHAR(60) NOT NULL); CREATE TABLE event ( id INTEGER PRIMARY KEY, club_id INTEGER NOT NULL, title VARCHAR(100) NOT NULL, FOREIGN KEY (club_id) REFERENCES club(id) ); SELECT conname, confrelid::regclass AS target, confdeltype FROM pg_constraint WHERE conrelid = 'event'::regclass AND contype = 'f';
| conname | target | confdeltype |
|---|---|---|
| event_club_id_fkey | club | a |
The error messages from this lesson in one place. In each one, the constraint name tells you which column has the problem.
OutputINSERT INTO student (student_no, first_name, last_name, department_id, year, enrollment_date)
VALUES ('202699001', 'Test', 'Student', 99, 1, DATE '2026-09-21');
ERROR: insert or update on table "student" violates foreign key constraint "student_department_id_fkey"
DELETE FROM department WHERE id = 1;
ERROR: update or delete on table "department" violates foreign key constraint
"instructor_department_id_fkey" on table "instructor"
CREATE TABLE club (id INTEGER, name VARCHAR(60) NOT NULL);
CREATE TABLE event (id INTEGER PRIMARY KEY, club_id INTEGER REFERENCES club(id));
ERROR: there is no unique constraint matching given keys for referenced table "club"