…
…
SQL and Database Fundamentals · Lesson 43 / 41 · Application
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 campus library lends books to students and writes everything in a notebook: which book is with whom, when it was borrowed, and when it is due back. To find out whether a book is on the shelf, someone has to scan the notebook page by page. In this lesson you will turn the notebook into two tables linked to the student records database and build the library from scratch.
This lesson brings together everything you have learned in one job. Since lesson 28 you have created tables, written constraints, linked tables with foreign keys, inserted and updated data, and built indexes. Each one was a separate lesson, and the task was always ready-made: "create these columns with this type". Real tasks do not arrive like that. The librarian will not give you a column list; she will describe her work. Turning those sentences into tables, types, and rules is your job.
Let's look at the end result first. When the library is built, a summary of the constraints of the two tables from the catalog gives you six rows:
| tablo | contype | adet |
|---|---|---|
| book | c | 2 |
| book | p | 1 |
| book | u | 1 |
| loan | c | 2 |
| loan | f | 2 |
| loan | p | 1 |
Each row is the trace of a rule: on book, two CHECK constraints, one primary key, and one uniqueness rule; on loan, two CHECK constraints, two foreign keys, and one primary key. The question that takes hours in the notebook, "Is *The Great Gatsby* on the shelf?", becomes a single query:
OutputSELECT b.title, b.copies, COUNT(l.id) AS on_loan, b.copies - COUNT(l.id) AS on_shelf
FROM book b
LEFT JOIN loan l ON l.book_id = b.id AND l.returned_on IS NULL
WHERE b.id = 5
GROUP BY b.title, b.copies;
title | copies | on_loan | on_shelf
------------------+--------+---------+----------
The Great Gatsby | 1 | 1 | 0You will write this query and others like it in the next lesson. The job of this lesson is to build the solid ground those queries will stand on.
In this lesson you will:
A database design usually follows the same steps. First you write the requirements: what the system will store and which rules it must follow. Then you pull the entities (tables) and the relationships between them out of those sentences. Next you choose the columns and types of each table and write the rules as constraints. Last, you load the data and try to break every rule on purpose. Starting with the tables is tempting, because writing CREATE TABLE feels concrete. But a table written before the rules are known has to be changed from the beginning when the rules appear.
Put the steps of designing a database in order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
When you talk to the librarian, these sentences come out:
1. Every book has a unique ISBN, a title, an author, and a publication year.
2. There can be several copies of the same book.
3. A student borrows a book; the loan period is 14 days.
4. When the book comes back, the return date is written down.
5. A student cannot borrow the same book a second time without returning it.
6. Past loans are not deleted; they are kept for reports.
The entities are the nouns in these sentences: book and student. The student table already exists in the case database, with 120 students. The book table will be new. And what is a "loan"? Over time a student borrows many books, and a book is borrowed by many students: the relationship is many-to-many. As you know from lesson 31, a many-to-many relationship is solved with a junction table. This junction table also has information of its own (borrow date, due date, return date), so we give it a name: loan.
What should the primary key of the junction table be? For club membership you wrote PRIMARY KEY (student_id, club_id), because the same student joins the same club once. Loans are different: the same student borrows the same book in October, returns it, and borrows it again in November. If the pair (book_id, student_id) were the primary key, the old October record would block the November loan. "The key of a junction table is always the pair of two foreign keys" is a common mistake; the pair is a key only if it really happens once. So loan gets its own id. We also do not write the book's title into the loan table: as you saw in lesson 32, that creates repetition and update anomalies, and book_id is enough.
Every requirement sentence turns into something in the database. Try the matching below; there is also a trap option in the list.
Match each requirement sentence with its counterpart in the database.
For each row, pick its match from the list, then check.
The columns of the book table come directly from the requirements. The only interesting decision is the type of the ISBN. An ISBN has thirteen digits and looks a lot like a number. Guess first:
Which type do you use to store an ISBN (for example 9780000000001)?
Let's see what would happen if you chose a number type. INTEGER holds numbers up to about 2.1 billion; a 13-digit ISBN is far above that:
OutputCREATE TABLE book_test (id INTEGER, isbn INTEGER);
INSERT INTO book_test VALUES (1, 9780000000001);
ERROR: integer out of rangeThe problem is not only size. Phone numbers, student numbers, and postal codes are all "codes that look like numbers", and they all ask the same question: will I calculate with it? If the answer is no, the type is text. The correct table looks like this:
Example 1 (case): The book table
CREATE TABLE book ( id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, isbn VARCHAR(13) NOT NULL UNIQUE, title VARCHAR(100) NOT NULL, author VARCHAR(60) NOT NULL, year INTEGER CHECK (year BETWEEN 1450 AND 2026), copies INTEGER NOT NULL DEFAULT 1 CHECK (copies > 0) ); INSERT INTO book (isbn, title, author, year) VALUES ('9780000000001', 'Introduction to Database Systems', 'A. Rivera', 2019), ('060000001X', 'Old Edition Dictionary', 'R. Ellis', 1950); SELECT id, isbn, title, copies FROM book ORDER BY id;
| id | isbn | title | copies |
|---|---|---|---|
| 1 | 9780000000001 | Introduction to Database Systems | 1 |
| 2 | 060000001X | Old Edition Dictionary | 1 |
(2 rows)
The number of the old dictionary stays exactly as it was, with its leading zero and its final X. For both books copies was not given, so the default 1 was used. The publication year is not required, because the year of an old donation may be unknown; but if it is written, it cannot be before the invention of printing or in the future. We chose BY DEFAULT because in the next step we want to load the sample books with their numbers.
The loan table carries most of the rules. Two foreign keys connect each loan to an existing book and an existing student. Two date rules compare two columns, so they are written at the table level.
Example 2 (case): The loan table and the constraint summary
CREATE TABLE loan ( id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, book_id INTEGER NOT NULL REFERENCES book(id), student_id INTEGER NOT NULL REFERENCES student(id), borrowed_on DATE NOT NULL, due_on DATE NOT NULL, returned_on DATE, CHECK (due_on > borrowed_on), CHECK (returned_on >= borrowed_on) );
After the book and loan tables are created, let's count the constraints from the catalog (NOT NULL rows are left out so they do not crowd the list):
SELECT conrelid::regclass AS tablo, contype, COUNT(*) AS adet FROM pg_constraint WHERE conrelid IN ('book'::regclass, 'loan'::regclass) AND contype <> 'n' GROUP BY 1, 2 ORDER BY 1, 2;
| tablo | contype | adet |
|---|---|---|
| book | c | 2 |
| book | p | 1 |
| book | u | 1 |
| loan | c | 2 |
| loan | f | 2 |
| loan | p | 1 |
(6 rows)
This is the table you saw at the start of the lesson. c is CHECK, f is a foreign key, p is a primary key, and u is a UNIQUE constraint.
Look closely at the second CHECK: returned_on >= borrowed_on. While the book is still with the student, returned_on is empty. It is easy to think "an empty return date is not greater than or equal to the borrow date, so the row is rejected", but that is not what happens. The rule from lesson 29 works here: a comparison with NULL gives an unknown result, and CHECK rejects only a row that is clearly false. So open loans are saved without a problem, and the rule starts to work the moment a return date is written. We also did not add ON DELETE CASCADE to the foreign keys: if a student is deleted, we do not want the loan history to disappear silently. The default behavior is to reject the deletion of a student who has loans.
What happened to the requirement "the loan period is 14 days"? The first idea is to leave the due date to the table: due_on DATE DEFAULT borrowed_on + 14. In the cell below, the two tables are ready. First run it as it is and see the column list. Then change the line due_on DATE NOT NULL, in the loan table to due_on DATE NOT NULL DEFAULT borrowed_on + 14,, run it again, and read the error message.
Try it now· not graded; doesn't affect progress
After the change, the message is cannot use column reference in DEFAULT expression: a default value cannot refer to another column. DEFAULT can only be a constant or an expression that does not depend on the row (such as 0, TRUE, or CURRENT_DATE). That is why the due date is calculated during the INSERT, with the date arithmetic you saw in lesson 27: DATE '2026-11-24' + 14.
The fifth requirement is the hardest: "A student cannot borrow the same book a second time without returning it." This looks like a uniqueness rule, but among which rows? Old, returned records also contain the same (book, student) pair.
How do you write the rule "the same student cannot borrow the same book a second time without returning it"?
In lesson 39 you built a uniqueness rule with CREATE UNIQUE INDEX. When you add a WHERE at the end, the index covers only the rows that meet this condition; this is called a partial index. A unique partial index looks for uniqueness only among those rows.
In the built library (9 books, 19 loans), student 17 still has book 3; book 6 was borrowed in October and returned. Let's create the rule and try to lend book 3 to student 17 again:
OutputCREATE UNIQUE INDEX loan_open ON loan (book_id, student_id) WHERE returned_on IS NULL;
INSERT INTO loan (book_id, student_id, borrowed_on, due_on)
VALUES (3, 17, DATE '2026-11-24', DATE '2026-11-24' + 14);
ERROR: duplicate key value violates unique constraint "loan_open"It was rejected: there is already an open loan for book 3. When we try to lend book 6 with the same index, the result is different:
INSERT INTO loan (book_id, student_id, borrowed_on, due_on) VALUES (6, 17, DATE '2026-11-24', DATE '2026-11-24' + 14); SELECT book_id, student_id, borrowed_on, due_on, returned_on FROM loan WHERE book_id = 6 AND student_id = 17 ORDER BY borrowed_on;
| book_id | student_id | borrowed_on | due_on | returned_on |
|---|---|---|---|---|
| 6 | 17 | 2026-10-05 | 2026-10-19 | 2026-10-25 |
| 6 | 17 | 2026-11-24 | 2026-12-08 | NULL |
(2 rows)
The October slip is closed, so it is not inside the index, and the new loan was accepted. If you had tried the same thing with UNIQUE (book_id, student_id), you would have got the error duplicate key value violates unique constraint "loan_book_id_student_id_key". One note: the only copy of *Crime and Punishment* is now with student 117, so the book we would lend to student 17 is not actually on the shelf. The rule "the number of open loans cannot be more than the number of copies" needs to count other rows, and neither a CHECK nor an index can write that. In lesson 44 you will make this check inside a transaction.
When the tables are built, the sample data is loaded. The setup file of the library (university-library.sql) adds these two tables, 9 books, and 19 loans to the case database. Today is November 24, 2026; we are lending book 2 to student 17:
Example 3 (case): The first loan
INSERT INTO loan (book_id, student_id, borrowed_on, due_on) VALUES (2, 17, DATE '2026-11-24', DATE '2026-11-24' + 14) RETURNING book_id, student_id, borrowed_on, due_on, returned_on;
| book_id | student_id | borrowed_on | due_on | returned_on |
|---|---|---|---|---|
| 2 | 17 | 2026-11-24 | 2026-12-08 | NULL |
(1 row)
The due date was calculated with date arithmetic, and returned_on is empty because it was never mentioned: the book is with the student.
Now the most important step. Writing a rule does not show that it works; a typo, a reversed sign, or a forgotten condition can leave a rule silently ineffective. That is why every rule is tried on purpose with a row that should break it, and you check that it is rejected.
The cell below runs on the built library database. First run it as it is: you see the loans of student 17. Then try the three commented-out breaking attempts one by one: delete the -- (a) part at the start of a line, run it, read the constraint name in the error message, and then put the marker back. (a) return date before the borrow date, (b) student 1200, who does not exist, (c) due date before the borrow date.
Try it now· not graded; doesn't affect progress
All three must be rejected: (a) violates check constraint "loan_check1" (the second CHECK, the return rule), (b) violates foreign key constraint "loan_student_id_fkey", (c) violates check constraint "loan_check" (the first CHECK, the due date rule). PostgreSQL gave the unnamed table-level CHECK constraints the names loan_check and loan_check1 in order; it is hard to remember which is which. If you name the constraint yourself with CONSTRAINT return_not_before_borrow CHECK (...), the error message explains the rule. A breaking attempt that is accepted is proof that the rule was written incompletely or wrongly.
The same pattern shows up in every booking system. A gym takes bookings for its classes: a member cannot sign up for the same class twice, but can sign up again for a class they canceled. The "open loan" of the library is the "booking that is not canceled" here.
Example 4 (outside the case): Gym booking
CREATE TABLE class_session ( id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name VARCHAR(40) NOT NULL, capacity INTEGER NOT NULL CHECK (capacity > 0) ); CREATE TABLE booking ( id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, session_id INTEGER NOT NULL REFERENCES class_session(id), member_name VARCHAR(40) NOT NULL, canceled BOOLEAN NOT NULL DEFAULT FALSE ); CREATE UNIQUE INDEX booking_active ON booking (session_id, member_name) WHERE NOT canceled; INSERT INTO class_session (name, capacity) VALUES ('Pilates', 12); INSERT INTO booking (session_id, member_name) VALUES (1, 'Maya'); UPDATE booking SET canceled = TRUE WHERE member_name = 'Maya'; INSERT booking (session_id, member_name) (1, ); id, session_id, member_name, canceled booking id;
| id | session_id | member_name | canceled |
|---|---|---|---|
| 1 | 1 | Maya | true |
| 2 | 1 | Maya | false |
(2 rows)
Maya signed up for Pilates, canceled, and signed up again. What happens now if INSERT INTO booking (session_id, member_name) VALUES (1, 'Maya'); is written a third time?
In the table above, Maya has one canceled and one active booking for Pilates. What happens if the same INSERT runs once more?
INSERT INTO booking (session_id, member_name) VALUES (1, 'Maya');
Most of the exercises and the next lesson work on university-library.sql: the case database, the book and loan tables, 9 books, and 19 loans. The partial index is not in the file; you will build it in exercise 4.
SELECT (SELECT COUNT(*) FROM book) AS book, (SELECT COUNT(*) FROM loan) AS loan, (SELECT COUNT(*) FROM loan WHERE returned_on IS NULL) AS open_loans;
| book | loan | open_loans |
|---|---|---|
| 9 | 19 | 9 |
(1 row)
Of the 19 loans, 9 are still open: the books are with students.
A fourth breaking attempt: there is no book number 99.
OutputINSERT INTO loan (book_id, student_id, borrowed_on, due_on)
VALUES (99, 17, DATE '2026-11-24', DATE '2026-12-08');
ERROR: insert or update on table "loan" violates foreign key constraint "loan_book_id_fkey"Writing the rules only in the application and not in the database. If you say "the loan screen already checks the dates" and skip CHECK, UNIQUE, and foreign keys, a bulk load, a manual fix, or a program written by another team can easily break the rules. Every path that does not use the screen skips the rule. The check on the screen is still useful, because it shows the user an early and clear message; but the constraint in the database is the last line of defense for the data. The second common mistake is writing a rule and never trying it. A reversed sign (< instead of >) or a condition written with = NULL instead of IS NULL goes unnoticed until you try a row that should break it.
id, and an empty returned_on passes the CHECK.CREATE UNIQUE INDEX ... WHERE returned_on IS NULL) looks for uniqueness only among open records; try every rule you build with a row that should break it and see that it is rejected.Next lesson: in the same library database you will query overdue loans, copies left on the shelf, and late fees, save the stock calculation as a view, and make lending and returning with a transaction.
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.
The name of a foreign key constraint is made of the table, the column, and the suffix _fkey; the message tells you which link broke.