…
…
SQL and Database Fundamentals · Lesson 29 / 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.
The club table you built in the last lesson accepts everything: a club with no name, a negative budget, two records for the same club, and rows with no ID. Student Affairs wants these mistakes to never reach the database. In this lesson you will write the rules into the table itself.
In lesson 28 you built a table from a requirement sentence: every column had a name and a type. A type tells a column what kind of value it can hold; you cannot put text into a NUMERIC column. But a type does not check whether a value makes sense. A negative budget is still a valid number, and a name left empty is still a valid NULL. First, let's see what a table without rules accepts.
Example 1 (case): A table with no rules accepts three bad rows
CREATE TABLE club (id INTEGER, name VARCHAR(60), budget NUMERIC(10, 2)); INSERT INTO club VALUES (1, 'Chess Club', 500), (1, 'Chess Club', -200), (NULL, NULL, NULL); SELECT * FROM club ORDER BY budget;
| id | name | budget |
|---|---|---|
| 1 | Chess Club | -200 |
| 1 | Chess Club | 500 |
| NULL | NULL | NULL |
(3 rows)
All three rows are in the table. The chess club is recorded twice and both records have ID 1, so nobody can say which one is the real club. One record has a negative budget. The third row has no ID and no name; it describes nothing, but it takes up space and adds one extra to every count. PostgreSQL did not object to any of this, because we never told it any rules.
In this lesson you will:
A constraint is a rule that decides which values can enter a table. When someone tries to insert a row that breaks the rule, the DBMS rejects the command and returns an error message; the row never enters the table. The real power of writing the rule into the table is this: the rule holds no matter which program, which person, or which route writes the data. A web form, a bulk upload file, or a hand-written query all pass through the same door.
There are five basic tools, and each one covers one kind of business rule. Before we open them up, try matching sentences to tools; we will go through each one in detail during the lesson.
Match each business rule with the tool that writes it into the table.
For each row, pick its match from the list, then check.
You have actually been working with constraints since day one. The student table in the case study database has 2 CHECK rules (year between 1 and 4, GPA between 0 and 4), 1 UNIQUE rule (a student number never repeats), and 8 NOT NULL rules in its definition. You never saw them, because so far you only read data. They become visible when you try to write a row that breaks them. Try adding a student in year 5:
OutputINSERT INTO student (student_no, first_name, last_name, department_id, year, enrollment_date)
VALUES ('202699001', 'Nina', 'Ortiz', 1, 5, '2026-09-15');
ERROR: new row for relation "student" violates check constraint "student_year_check"The error message tells you three things: which table (student), which kind of rule (check constraint), and which named rule (student_year_check) you hit. PostgreSQL generated the name: the table name, the column name, and the constraint type joined with underscores. If you try to add the same row as a year 2 student but with a student number that already exists, 202303001, a different rule fires this time:
OutputERROR: duplicate key value violates unique constraint "student_student_no_key"duplicate key means "this value already exists", and the _key suffix at the end is the name of a UNIQUE rule. An error message looks scary the first time you read it, but it is really a cheat sheet: it tells you which rule you broke, by name.
NOT NULL says the column cannot be left empty. Every club must have a name, so you write name VARCHAR(60) NOT NULL. Which columns are required is a design decision: a club's name is required, but its founding date may be unknown; if you make the date required, you cannot record a club whose date you do not know.
DEFAULT sets the value to use when a row is inserted without a value for that column. DEFAULT is not a constraint and it never rejects a row, but it is written in the same place as the constraints in a column definition, and it often appears together with NOT NULL. Let's look at an example from outside the university: in a café's order table, the quantity is usually 1, and a newly arrived order always has the status "pending".
Example 2 (not the case): A café order
CREATE TABLE cafe_order ( id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, item VARCHAR(30) NOT NULL, quantity INTEGER NOT NULL DEFAULT 1 CHECK (quantity > 0), status VARCHAR(12) NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'ready', 'delivered')) ); INSERT INTO cafe_order (item) VALUES ('latte'); INSERT INTO cafe_order (item, quantity, status) VALUES ('muffin', 3, 'ready'); SELECT * FROM cafe_order ORDER BY id;
| id | item | quantity | status |
|---|---|---|---|
| 1 | latte | 1 | pending |
| 2 | muffin | 3 | ready |
(2 rows)
A column definition is longer now: the name, the type, and then the rules, separated by spaces. The order of the rules is free; NOT NULL DEFAULT 1 and DEFAULT 1 NOT NULL mean the same thing. In the second row, the quantity and status were given, so the defaults did not apply. The first row had only the item name. Predict: what happened to the other columns?
A row was inserted into the cafe_order table above with only the item name. What are quantity and status in this row?
INSERT INTO cafe_order (item) VALUES ('latte');
There is a common misunderstanding about DEFAULT: "If I write NULL explicitly, the default still applies." It does not. DEFAULT works only when the column is not mentioned in the INSERT at all. Writing NULL means "let this column's value be NULL", and PostgreSQL carries out that request as written. Let's see the difference in a small table: a table with quantity INTEGER DEFAULT 1 and no NOT NULL.
OutputCREATE TABLE s (id INTEGER, quantity INTEGER DEFAULT 1);
INSERT INTO s VALUES (1, NULL); -- quantity explicitly NULL
INSERT INTO s (id) VALUES (2); -- quantity not mentioned at all
SELECT * FROM s ORDER BY id;
id | quantity
----+----------
1 | NULL
2 | 1The quantity of the first row stayed NULL, and the second one became 1. In the café table, quantity is also NOT NULL, so writing NULL explicitly makes the row be rejected: null value in column "quantity" of relation "cafe_order" violates not-null constraint. The lesson: DEFAULT fills a gap but does not forbid a gap; forbidding is the job of NOT NULL. Together they say "if no value is given, put this one in, but never leave it empty."
UNIQUE says the values in a column cannot repeat: name VARCHAR(60) UNIQUE blocks a second club with the same name, and the second attempt gets the error duplicate key value violates unique constraint "club_name_key". An email address, a student number, and a course code are columns like this.
The relationship between UNIQUE and NULL is surprising. Remember the rule from lesson 7: NULL is equal to nothing, not even to another NULL. UNIQUE says "no two values can be equal"; since two NULLs are not counted as equal, both get in. Predict first:
In a column defined as email VARCHAR(80) UNIQUE, can two rows have a NULL email?
Here is what happens in a small subscriber table:
OutputCREATE TABLE subscriber (id INTEGER, email VARCHAR(80) UNIQUE);
INSERT INTO subscriber VALUES (1, NULL), (2, NULL), (3, 'a@b.c');
INSERT INTO subscriber VALUES (4, 'ada@mail.example'), (5, 'ADA@mail.example');
SELECT * FROM subscriber ORDER BY id;
id | email
----+------------------
1 | NULL
2 | NULL
3 | a@b.c
4 | ada@mail.example
5 | ADA@mail.exampleAll five rows got in. We explained the two NULLs. What about the last two rows? To a person, ada@mail.example and ADA@mail.example are the same address, but to PostgreSQL they are two different strings. As you saw in lesson 26 when you cleaned dirty emails, letter case is part of the text. UNIQUE does not ignore the difference between uppercase and lowercase. This is why cleaning the data before writing it (LOWER) is still necessary; a uniqueness rule that ignores letter case can also be built, and you will see it with indexes in lesson 39.
PRIMARY KEY is the primary key you met in lessons 2 and 14. Technically it is NOT NULL and UNIQUE combined, but it is more than that: a table has only one, it is the identity of the row, and other tables refer to it. Think of an ID card number: everyone has one, no two people share the same one, and it cannot be left empty. If you try to write NULL into a primary key, the NOT NULL half fires: null value in column "id" of relation "t" violates not-null constraint.
Who provides the value of the primary key is also a decision. If you pick the numbers by hand, you have to deal with problems like two people picking the same number at the same time, or a number being forgotten. If you write id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, PostgreSQL gives each new row the next number itself:
OutputCREATE TABLE club (id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name VARCHAR(60));
INSERT INTO club (name) VALUES ('Chess'), ('Hiking'), ('Robotics');
SELECT * FROM club ORDER BY id;
id | name
----+----------
1 | Chess
2 | Hiking
3 | RoboticsThe id was never mentioned in the INSERT; PostgreSQL produced the numbers. The word ALWAYS forbids writing a number by hand: the command INSERT INTO club (id, name) VALUES (7, 'Drama') is rejected with the error cannot insert a non-DEFAULT value into column "id". If you write BY DEFAULT instead of ALWAYS, the number still comes automatically, but writing a value by hand is also possible. The tables in the case study database use BY DEFAULT, because the sample data was loaded together with its numbers. In older systems you may see the SERIAL type used for the same job.
Sometimes the identity of a row is not in one column but in the combination of two columns. Think about student club memberships: a student can be a member of many clubs, and a club can have many members, but the same student cannot join the same club twice. Neither student_id alone nor club_id alone is unique; the pair is. In this case the primary key is written after the column definitions, on a separate line: PRIMARY KEY (student_id, club_id). This is called a composite key.
You saw the same idea in the enrollment table of the case study in lesson 14: the rule UNIQUE (student_id, offering_id) blocks a student from enrolling in the same section twice. There the table's own id number is the primary key and the pair is UNIQUE; here the pair itself is the primary key. Both say "this pair happens once." In the cell below, the table and three memberships are ready. Run it, then try the two tasks under it.
Try it now· not graded; doesn't affect progress
1. Before the SELECT, add the line INSERT INTO club_member VALUES (1, 1); and run it. Which constraint name appears in the error message? (club_member_pkey: the name of a primary key rule ends with _pkey.)
2. Delete that line and write INSERT INTO club_member VALUES (2, 2); instead. This time you should see four rows: student 2 was already a member of club 1, but club 2 is a new pair for them.
CHECK writes a condition that every row must satisfy. The condition is written in the same language as the conditions you write in WHERE: comparison, BETWEEN, IN, AND, OR. budget NUMERIC(10, 2) CHECK (budget >= 0) blocks a negative budget; CHECK (year BETWEEN 1 AND 4) in the case study blocked year 5; CHECK (status IN ('pending', 'ready', 'delivered')) in the café table blocks a status that is not on the list. Now let's bring all the tools together in the club table.
Example 3 (case): The club table with rules
CREATE TABLE club ( id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name VARCHAR(60) NOT NULL UNIQUE, budget NUMERIC(10, 2) NOT NULL DEFAULT 0 CHECK (budget >= 0), active BOOLEAN NOT NULL DEFAULT TRUE, founded DATE ); INSERT INTO club (name) VALUES ('Chess Club'); SELECT * FROM club;
| id | name | budget | active | founded |
|---|---|---|---|---|
| 1 | Chess Club | 0 | true | NULL |
(1 row)
Only the name was given. PostgreSQL produced the number, the budget and the active flag took their default values, and the founding date stayed NULL because it is not required and has no default. When you write INSERT INTO club (name, budget) VALUES ('Theater', -500); in the same table, the command is rejected:
OutputERROR: new row for relation "club" violates check constraint "club_budget_check"Some rules cannot be described with a single column. An event's end date cannot be before its start date; this rule compares two columns. Such a CHECK is written on a separate line after the column definitions, at the table level:
OutputCREATE TABLE event (
id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title VARCHAR(100) NOT NULL,
start_date DATE NOT NULL,
end_date DATE NOT NULL,
CHECK (end_date >= start_date)
);
INSERT INTO event (title, start_date, end_date)
VALUES ('Chess tournament', '2026-12-12', '2026-12-10');
ERROR: new row for relation "event" violates check constraint "event_check"This time the constraint name has no column name (event_check), because the rule does not belong to a single column. An event that starts and ends on the same day ('2026-12-15', '2026-12-15') does get in; >= accepts equality too.
There is also a trap between CHECK and NULL. CHECK rejects a row when the condition is false. You saw three-valued logic in lesson 7: a comparison that contains NULL is neither true nor false; it is unknown. CHECK does not reject unknown. Predict first:
In the fund table, budget NUMERIC CHECK (budget >= 0) is defined, and the column has no NOT NULL. What does this command do?
INSERT INTO fund VALUES (2, NULL);
This is why the club table with rules has both NOT NULL and CHECK on the budget column. One says "it cannot be empty", the other says "if it is filled, it cannot be negative." CHECK alone does not fully cover the rule "the budget must be zero or more"; an empty budget passes through the door.
Now try the main skill of the lesson: look at a table definition and say which row will get in, without running it. In the cell below, the club table with rules and one row are ready. Under it, four INSERTs wait as comments:
('Theater'): name only('Theater', -500): negative budget(NULL, 100): a club with no name('Chess Club'): the same name a second timeBefore you run anything, write your prediction for each one: does it get in, and if not, which constraint name appears in the error message? Then, one at a time, delete the -- at the start of a line, run it, and compare the constraint name in the error message with your prediction. After each attempt, put the marker back; the cell rebuilds the table from scratch on every run.
Try it now· not graded; doesn't affect progress
When you uncomment a line, delete the whole -- (a) part at the start. The results: (a) gets in and the table has two rows; Theater's budget is 0 and its active flag is true. (b) is rejected by club_budget_check. (c) is rejected with null value in column "name": this is a NOT NULL rule. (d) is rejected by club_name_key: this is the UNIQUE rule. When a command is rejected, the rest of the cell does not run either, and you see an error instead of the result table; the table is not damaged.
So far PostgreSQL produced the names in the error messages. You can also name a constraint yourself: CONSTRAINT budget_not_negative CHECK (budget >= 0). Then the error message says violates check constraint "budget_not_negative". A good name explains the rule to the person who reads the error; also, in lesson 33, when you want to drop or change a constraint, you will refer to it by its name.
All the constraints of a table are recorded in the system catalog table pg_constraint. For the club table with rules:
OutputSELECT contype, pg_get_constraintdef(oid) AS definition
FROM pg_constraint
WHERE conrelid = 'club'::regclass
ORDER BY contype, 2;
contype | definition
---------+------------------------------------
c | CHECK ((budget >= (0)::numeric))
n | NOT NULL active
n | NOT NULL budget
n | NOT NULL id
n | NOT NULL name
p | PRIMARY KEY (id)
u | UNIQUE (name)contype gives the type of the constraint as a single letter: c CHECK, n NOT NULL, p primary key, u UNIQUE. We did not write NOT NULL for id, but it is in the list: it is the NOT NULL half of the primary key. DEFAULT is not in the list, because it is not a constraint. The check queries in the exercises read your table from this catalog. You will also see an f type: foreign key, the topic of the next lesson.
The lines of a table definition are also written in a certain order: first the table name and the opening parenthesis, then each column with its own rules, separated by commas, and finally the closing parenthesis. Put the lines of the member table below in the right order.
Put the lines of this member table in order: the ID comes automatically, the name is required, the email is required and unique, and the score is 0 if not given and stays between 0 and 100.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
Constraints do the same job in every database. The Earbud music app database has rules too: a listening time cannot be zero or negative, a plan can be only one of two kinds, and a listener can like the same song only once. Let's read the constraints of the Earbud tables from the catalog (without the NOT NULL rows, so they do not crowd the output).
Example 4 (not the case): Earbud's rules
SELECT conrelid::regclass AS table_name, contype, pg_get_constraintdef(oid) AS definition FROM pg_constraint WHERE conrelid IN ('listener'::regclass, 'play'::regclass, 'song_like'::regclass) AND contype IN ('c', 'p', 'u') ORDER BY 1, 2;
| table_name | contype | definition |
|---|---|---|
| listener | c | CHECK (((plan)::text = ANY ((ARRAY['free'::character varying, 'premium'::character varying])::text[]))) |
| listener | p | PRIMARY KEY (id) |
| listener | u | UNIQUE (nickname) |
| play | c | CHECK ((seconds_played > 0)) |
| play | p | PRIMARY KEY (id) |
| song_like | p | PRIMARY KEY (listener_id, song_id) |
(6 rows)
Do not let the long CHECK line in the listener table scare you: PostgreSQL converts the rule plan IN ('free', 'premium') into its own internal form and stores it that way. The song_like table has a composite key: the same listener-song pair is liked once. If you try to add a new listener with the 'family' plan, listener_plan_check fires; listener 1 liking song 1 a second time is rejected by song_like_pkey.
In Earbud, the plan column must accept only the value 'free' or 'premium'. Which tool writes this rule?
When you read the constraints of the case study's student table from the catalog, the rules we counted in step 1 appear.
SELECT contype, pg_get_constraintdef(oid) AS definition FROM pg_constraint WHERE conrelid = 'student'::regclass ORDER BY contype, 2;
| contype | definition |
|---|---|
| c | CHECK (((gpa >= (0)::numeric) AND (gpa <= (4)::numeric))) |
| c | CHECK (((year >= 1) AND (year <= 4))) |
| f | FOREIGN KEY (advisor_id) REFERENCES instructor(id) |
| f | FOREIGN KEY (department_id) REFERENCES department(id) |
| n | NOT NULL department_id |
| n | NOT NULL enrollment_date |
| n | NOT NULL first_name |
| n |
Checking a rule only in the application (a web form, a Python program) and not writing it into the table. A form can block a negative budget, but someone who enters data through another route is not blocked: a bulk upload file, a program written by another team, a nightly transfer, or a single INSERT typed by hand. If the rule lives only in the form, the data breaks at the first opportunity, and finding the bad row later costs much more than stopping it at the door.
Always write the important rules into the table as constraints. The check in the form is still useful: it shows the user a message earlier and in plainer words ("The budget cannot be negative" is friendlier than club_budget_check). But the last word belongs to the table.
PRIMARY KEY (student_id, club_id).GENERATED ALWAYS AS IDENTITY lets the database give the number.Next lesson: the club's events will live in a separate table; to stop events from being written for a club that does not exist, we will link the two tables with a foreign key (FOREIGN KEY).
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.
| n | NOT NULL id |
| n | NOT NULL last_name |
| n | NOT NULL student_no |
| n | NOT NULL year |
| p | PRIMARY KEY (id) |
| u | UNIQUE (student_no) |
(14 rows)
Two CHECKs, eight NOT NULLs, one primary key, one UNIQUE. BETWEEN 1 AND 4 is stored in the catalog as >= 1 AND <= 4. The two f rows are foreign keys: department_id and advisor_id point to other tables, and in the next lesson you will write this kind of rule yourself. The gpa column has a CHECK but no NOT NULL: the GPA of first-year students who do not have grades yet can stay empty.
Let's try to enter an order with a status that is not on the list into the cafe_order table from Example 2.
OutputINSERT INTO cafe_order (item, status) VALUES ('tea', 'canceled');
ERROR: new row for relation "cafe_order" violates check constraint "cafe_order_status_check"The value 'canceled' is not in the IN list, so the condition comes out false and the row is rejected. If the café wants to add a new status, it has to change the rule; you will do this with ALTER TABLE in lesson 33.