…
…
SQL and Database Fundamentals · Lesson 44 / 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 library database is set up and two and a half months of loans have been entered: 9 books and 19 loans. Every morning the librarian asks the same three questions: which books are with students, who is late, and which book has no copy left on the shelf. In this lesson you will answer them with SQL and also calculate the late fines for the end-of-term report.
In the previous lesson you built the two tables of the library: book (id, ISBN, title, author, year, number of copies copies) and loan (which book, which student, borrow date, due date, return date). Student names are in the student table as usual. In this lesson "today" is November 24, 2026, and queries write it as DATE '2026-11-24'; in a real system you would use CURRENT_DATE instead (lesson 27). This is the screen the librarian wants to see every morning:
| Question | Answer |
|---|---|
| Who is late? | 3 people: Lena Nakamura 21 days, Ayesha Singh 16 days, Omar Nguyen 7 days |
| Is any book out of copies on the shelf? | 2 books: The Great Gatsby and Crime and Punishment |
Behind these two lines there are joins, filters, grouping and a view. All the tools you learned in this course will work together here.
In this lesson you will:
"Who is late?" is a short question, but before you turn it into SQL it needs a definition. Who is late? A student who still has the book and whose due date is before today. This definition writes the WHERE line of the query for you: the return date is empty and the due date is less than today. A report written without defining the term often answers the wrong question; for example, it also counts someone who returned the book late but has already brought it back. Once the definition is clear, the tables come next: loan data is in loan, the name is in student, the title is in book. After that come the joins (lessons 15–17), the filter, grouping if needed (12–13), and a readable sort order.
Put the order of thinking for turning a report question into SQL in order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
Let's turn the definition into SQL. A date difference gives a number of days: DATE '2026-11-24' - l.due_on shows how many days have passed (lesson 27).
Example 1 (case): The late loans
SELECT s.first_name, s.last_name, b.title, l.due_on, DATE '2026-11-24' - l.due_on AS days_late FROM loan l JOIN student s ON s.id = l.student_id JOIN book b ON b.id = l.book_id WHERE l.returned_on IS NULL AND l.due_on < DATE '2026-11-24' ORDER BY days_late DESC;
| first_name | last_name | title | due_on | days_late |
|---|---|---|---|---|
| Lena | Nakamura | Python Programming | 2026-11-03 | 21 |
| Ayesha | Singh | The Great Gatsby | 2026-11-08 | 16 |
| Omar | Nguyen | Introduction to Statistics | 2026-11-17 | 7 |
Three tables, two JOINs and two conditions. Every part of the definition found a place in the query: "still has it" became l.returned_on IS NULL, and "past the due date" became l.due_on < DATE '2026-11-24'. If you had written the same query with l.returned_on = NULL, no row would come back. Remember from lesson 7: NULL is not equal to anything, not even to NULL; = NULL gives an unknown result on every row and WHERE drops that row. There is no error message either, you only see an empty list. An empty late list looks like "everyone is on time" to the librarian, so this mistake is silent and dangerous.
The cell below runs on the library database. Run it, then change the two '2026-11-24' values to '2026-12-01': one week later the list grows to 6 people and Lena Nakamura's delay goes up to 28 days. Then change IS NULL to = NULL and watch the result go empty.
Try it now· not graded; doesn't affect progress
The second question on the morning screen: which book has a copy left on the shelf? This number is not written in any column. book.copies is the number of copies the library owns; the number on the shelf is found by subtracting the number of open (not returned) loans from it. Every book must appear in the list, including the ones with no open loan. So book is on the left and loan is attached to it with a LEFT JOIN (lesson 16). The open-loan condition l.returned_on IS NULL belongs to the right table. So where do you write it?
In the query that finds the number of copies left on the shelf for each book, where should the open-loan condition (l.returned_on IS NULL) go so that all 9 books stay in the list?
SELECT b.title, b.copies - COUNT(l.id) AS on_shelf FROM book b LEFT JOIN loan l ON l.book_id = b.id -- does the condition go here, or in ON? GROUP BY b.id, b.title, b.copies;
The right answer is ON. WHERE drops rows after the join is finished. The only loan of Data Visualization was returned in October; the LEFT JOIN matches the book with that loan, and since returned_on is filled, WHERE drops the row and the book vanishes from the report. When the condition is in ON, no open loan matches; the LEFT JOIN keeps the book with a row whose right side is empty, and COUNT(l.id) counts 0.
The stock calculation is needed not only on the morning screen but also on the loan screen, in the monthly report and on the library's web page. Writing the same query again everywhere means that one day someone will move the condition to WHERE. As you learned in lesson 38, you save the calculation once as a view:
Example 2 (case): The `book_status` view
CREATE VIEW book_status AS SELECT b.id, 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 GROUP BY b.id, b.title, b.copies; SELECT * FROM book_status ORDER BY id;
| id | title | copies | on_loan | on_shelf |
|---|---|---|---|---|
| 1 | Introduction to Database Systems | 3 | 1 | 2 |
| 2 | Data Analysis with SQL | 2 | 1 | 1 |
| 3 | Python Programming | 3 | 2 | 1 |
| 4 | Introduction to Statistics | 2 | 1 | 1 |
| 5 | The Great Gatsby | 1 | 1 | 0 |
| 6 | Crime and Punishment | 1 | 1 | 0 |
| 7 | Animal Farm |
The second line of the morning screen is now a single sentence: SELECT title FROM book_status WHERE on_shelf = 0; The Great Gatsby and Crime and Punishment.
A question comes to mind: "Wouldn't it be simpler to write the shelf count into the book table as a column?" No. on_shelf is a derived value: it is calculated from other columns. If you store it, you must also update it at every loan and every return; if someone forgets once, the number in the table contradicts reality and nobody knows which one is right. A view stores nothing; it recalculates from the loan table every time it is read, so it is always current. See it in the cell below: run it, then add the line INSERT INTO loan (book_id, student_id, borrowed_on, due_on) VALUES (9, 60, DATE '2026-11-24', DATE '2026-12-08'); between the view and the SELECT and run it again. The shelf count of Data Visualization drops from 2 to 1 without anyone touching it.
Try it now· not graded; doesn't affect progress
Think of the library desk: the librarian checks the shelf, prints the slip, hands over the book. If one of these steps stays half done, the record is broken. Lending a book in a database is also two steps: checking whether a copy is on the shelf, and adding the loan row. As in lesson 37, you do these steps inside one transaction; you check the result, then write COMMIT if it is right and ROLLBACK if it is wrong. Student 60 (Hiro Kim) takes book 1 today for 14 days:
OutputBEGIN;
INSERT INTO loan (book_id, student_id, borrowed_on, due_on)
VALUES (1, 60, DATE '2026-11-24', DATE '2026-11-24' + 14);
SELECT * FROM book_status WHERE id = 1;
COMMIT;
id | title | copies | on_loan | on_shelf
1 | Introduction to Database Systems | 3 | 2 | 1A return is also an UPDATE (lesson 35): the returned_on column of the open loan is filled with today's date. The loan row is not deleted; the past record stays, and the late calculation and the "most borrowed" report depend on it. The partial unique index you built in lesson 43 (loan_open) looks only at open loans, so the same student can borrow a returned book again. So how do you protect the last copy?
The only copy of The Great Gatsby is with student 34 (on_shelf is 0). The librarian adds a loan row for student 60 for The Great Gatsby without checking. Does the database prevent this second loan?
INSERT INTO loan (book_id, student_id, borrowed_on, due_on) VALUES (5, 60, DATE '2026-11-24', DATE '2026-11-24' + 14);
If two librarians lend the same last copy at the same moment, both may see "on_shelf is 1". To prevent this, the row being checked is locked (SELECT ... FROM book WHERE id = 5 FOR UPDATE); this is outside the scope of this course, but it is good to know the name.
The end-of-term report: each student's total delay and fine, $0.10 per day. Watch out for a misunderstanding here: a delay does not exist only for books that are still out. Ali Ahmed brought back *Data Analysis with SQL* 7 days after the due date; it was returned, but late. The delay is counted from the due date to the return date for a returned loan, and from the due date to today for an open loan. The COALESCE from lesson 7 combines the two in one expression: COALESCE(returned_on, DATE '2026-11-24') - due_on. If the return date is empty, today is used instead. If the result is negative, the book came back early; those rows are filtered out. We use a CTE to make the calculation a named step (lesson 23):
Example 3 (case): The late fine
WITH d AS ( SELECT student_id, COALESCE(returned_on, DATE '2026-11-24') - due_on AS days FROM loan ) SELECT s.first_name, s.last_name, SUM(d.days) AS days_late, SUM(d.days) * 0.10 AS fine FROM d JOIN student s ON s.id = d.student_id WHERE d.days > 0 GROUP BY s.id, s.first_name, s.last_name ORDER BY days_late DESC, s.last_name;
| first_name | last_name | days_late | fine |
|---|---|---|---|
| Lena | Nakamura | 27 | 2.70 |
| Ayesha | Singh | 16 | 1.60 |
| Ali | Ahmed | 7 | 0.70 |
| Omar | Nguyen | 7 | 0.70 |
| Anika | Rivera | 3 | 0.30 |
Lena Nakamura's 27 days are the sum of two loans: the Python Programming book she still has is 21 days late, and *Crime and Punishment*, which she returned 6 days late in October. If you had looked only at open loans, the report would have stayed at 3 people, and Ali Ahmed and Anika Rivera would have looked fine. Ali Ahmed and Omar Nguyen are tied; the second sort key (last name) decides the order when there is a tie.
Try it in the cell: change the daily fine to $0.15 and add HAVING SUM(d.days) > 10 under the GROUP BY line (lesson 13). Only people who are more than 10 days late remain: Lena Nakamura $4.05 and Ayesha Singh $2.40.
Try it now· not graded; doesn't affect progress
The most borrowed books, ranked with RANK:
SELECT b.title, COUNT(*) AS loans, RANK() OVER (ORDER BY COUNT(*) DESC) AS rank FROM loan l JOIN book b ON b.id = l.book_id GROUP BY b.id, b.title ORDER BY rank, b.title LIMIT 3;
| title | loans | rank |
|---|---|---|
| Data Analysis with SQL | 4 | 1 |
| Introduction to Database Systems | 4 | 1 |
| Python Programming | 3 | 3 |
Two books are first with 4 loans each; RANK gives ties the same rank and starts the next one at 3. The change from month to month is found with LAG: 2 loans in September, 8 in October, 9 in November; the difference is 6 in October and 1 in November. To get these reports with one click at the end of the term in a real library, you can turn them into views as well.
The queries are ready; before you open the system to real users, two things are still missing. The first is permissions (lesson 40): the librarian enters book and loan records and updates the return date, but the history is never deleted. So the librarian role gets SELECT, INSERT and UPDATE on the book and loan tables, and no DELETE. The reporting team only sees the stock: SELECT on the book_status view is enough for it. The second is speed (lesson 39): the screens "this student's loans" and "this book's loans" are opened hundreds of times a day; the indexes loan (student_id) and loan (book_id) speed up these lookups. Match each need with the tool that meets it:
Match each need of the library system with the tool that meets it. One tool is extra.
For each row, pick its match from the list, then check.
Each of these steps was a tool you learned in a separate lesson. When they come together, they form a system that is reliable (constraints and transactions), fast (indexes), secure (roles) and queryable (views and reports).
The same order of thinking works for any job. The school snack bar has moved its tab book into a table: each row is a purchase, and if paid_on is empty, the debt still stands. The snack bar owner asks "who owes how much?" First the term: the debt is the sum of the unpaid rows. Paid rows also stay in the table, so skipping the condition gives a wrong result.
Maya has two rows: $2.25 unpaid and $1.50 paid. Which condition gives the correct debt per student?
Example 4 (outside the case): The unpaid debts
CREATE TABLE snack_tab (student_name VARCHAR(30) NOT NULL, amount NUMERIC(5,2) NOT NULL, paid_on DATE); INSERT INTO snack_tab VALUES ('Maya', 2.25, NULL), ('Maya', 1.50, DATE '2026-11-20'), ('Noah', 3.00, DATE '2026-11-18'), ('Noah', 1.25, NULL), ('Zara', 1.75, NULL), ('Zara', 2.00, NULL), ('Leo', 2.50, DATE '2026-11-21'); SELECT student_name, SUM(amount) AS owed FROM snack_tab WHERE paid_on IS NULL GROUP BY student_name ORDER BY owed DESC;
| student_name | owed |
|---|---|
| Zara | 3.75 |
| Maya | 2.25 |
| Noah | 1.25 |
Leo is not in the list because he owes nothing now. In the sum with no condition, Noah would appear at the top with $4.25; but $3.00 of his debt was already paid. The returned_on in the library and the paid_on here play the same role: if it is empty, the matter is still open.
With this lesson the course is complete. In the first lesson you started by asking what a database is; now you can design and build a database, change data safely, and produce reports that answer real questions from it.
Student 17 (Lena Nakamura) returns the Python Programming book she has (book 3) today and immediately borrows it again for 14 days. With the partial unique index in place, the order matters: first the open loan is closed, then the new row is added. Both are done in one transaction.
CREATE UNIQUE INDEX loan_open ON loan (book_id, student_id) WHERE returned_on IS NULL; BEGIN; UPDATE loan SET returned_on = DATE '2026-11-24' WHERE book_id = 3 AND student_id = 17 AND 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); COMMIT; SELECT borrowed_on, due_on, returned_on FROM loan WHERE book_id = 3 AND student_id = 17 ORDER BY borrowed_on;
| borrowed_on | due_on | returned_on |
|---|---|---|
Writing a condition that belongs to the right table in a LEFT JOIN report into WHERE:
OutputSELECT b.id, b.title, b.copies - COUNT(l.id) AS on_shelf
FROM book b
LEFT JOIN loan l ON l.book_id = b.id
WHERE l.returned_on IS NULL
GROUP BY b.id, b.title, b.copies;
(8 rows)The query gives no error and the result looks believable, but books whose loans have all been returned drop out of the list. In this data, Data Visualization (book 9), which has both copies on the shelf, disappears and the stock report returns 8 rows instead of 9. A filter condition on the right table is written in ON: LEFT JOIN loan l ON l.book_id = b.id AND l.returned_on IS NULL. After you write a report, comparing its row count with the number of books catches this mistake right away.
IS NULL, and in a LEFT JOIN the condition on the right table goes in ON.COALESCE(returned_on, today) - due_on, so it also covers loans that were returned.Next lesson: none; this was the last lesson of the course SQL Database Applications. Congratulations, you completed the course; apply what you learned to your own database project.
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.
| 1 |
| 1 |
| 8 | Algorithms | 2 | 1 | 1 |
| 9 | Data Visualization | 2 | 0 | 2 |
| 2026-10-20 |
| 2026-11-03 |
| 2026-11-24 |
| 2026-11-24 | 2026-12-08 | NULL |
The old loan was not deleted, its return date was filled; its 21-day delay stays in the reports. If the order were reversed, the INSERT would hit the loan_open index.
CREATE ROLE librarian; GRANT SELECT, INSERT, UPDATE ON book, loan TO librarian; SELECT has_table_privilege('librarian', 'loan', 'INSERT') AS can_insert, has_table_privilege('librarian', 'loan', 'DELETE') AS can_delete;
| can_insert | can_delete |
|---|---|
| true | false |
The role can add records but cannot delete them: the loan history is protected. A row entered by mistake is not deleted, it is fixed with UPDATE.