Reading history

SQL Project: Library Database

7 min read Updated 0 views

Design and query a library database in SQL: tables with constraints, books on loan, available copies, overdue fines, popular authors and inactive members.

In this project you will design and query a small library database from scratch. It brings together table design, constraints, joins, aggregation, NOT EXISTS, date arithmetic and window functions to answer the questions a real librarian asks: which books are out, how many copies are left, who is late and what they owe, and which authors are most popular.

In this project you will

  • Design four related tables with keys and CHECK constraints
  • List books currently on loan and copies still on the shelf
  • Calculate days overdue and late fines
  • Rank authors by popularity and find inactive members
  • See constraints rejecting bad data

You should know constraints, joins, EXISTS and top N per group.

1. Design the Tables

authorsid PKnamebooksid PKtitleauthor_id FKcopies CHECK >= 0membersid PKnamejoinedloansid PKbook_id FKmember_id FKborrowed_ondue_onreturned_on (NULL = out)1 : many1 : many1 : many

A book has one author, and a member can borrow many books over time. The loans table links books and members, one row per borrowing. returned_on stays NULL until the book comes back.

CREATE TABLE authors (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE books (
  id        INTEGER PRIMARY KEY,
  title     TEXT NOT NULL,
  author_id INTEGER NOT NULL REFERENCES authors(id),
  copies    INTEGER NOT NULL CHECK (copies >= 0)
);
CREATE TABLE members (
  id     INTEGER PRIMARY KEY,
  name   TEXT NOT NULL,
  joined TEXT NOT NULL
);
CREATE TABLE loans (
  id          INTEGER PRIMARY KEY,
  book_id     INTEGER NOT NULL REFERENCES books(id),
  member_id   INTEGER NOT NULL REFERENCES members(id),
  borrowed_on TEXT NOT NULL,
  due_on      TEXT NOT NULL,
  returned_on TEXT,                      -- NULL while the book is still out
  CHECK (due_on > borrowed_on)
);
INSERT INTO authors VALUES (1,'Humayun Ahmed'),(2,'Rabindranath Tagore'),(3,'Kazi Nazrul Islam'),(4,'Muhammed Zafar Iqbal');
INSERT INTO books VALUES
 (1,'Himu',1,3),(2,'Gitanjali',2,2),(3,'Agnibina',3,1),(4,'Amar Bondhu Rashed',4,2),(5,'Misir Ali',1,2),(6,'Shesher Kobita',2,1);
INSERT INTO members VALUES (1,'Rahim','2026-01-10'),(2,'Sadia','2026-02-01'),(3,'Tanvir','2026-02-20'),(4,'Mim','2026-03-05');
INSERT INTO loans VALUES
 (1,1,1,'2026-03-01','2026-03-15','2026-03-12'),
 (2,2,1,'2026-03-10','2026-03-24','2026-03-30'),
 (3,1,2,'2026-03-05','2026-03-19',NULL),
 (4,4,2,'2026-03-20','2026-04-03','2026-04-01'),
 (5,1,3,'2026-03-22','2026-04-05',NULL),
 (6,5,1,'2026-04-02','2026-04-16',NULL),
 (7,4,3,'2026-04-04','2026-04-18','2026-04-10');
  • REFERENCES creates foreign keys, so a loan must point to a real book and member.
  • CHECK (copies >= 0) and CHECK (due_on > borrowed_on) block impossible values.
  • Dates are stored as ISO text (YYYY-MM-DD), which sorts and compares correctly in SQLite.

2. What Is Out and What Is Left?

-- 1. Books that are out right now, with who has them
SELECT b.title, m.name AS member, l.due_on
FROM loans AS l
JOIN books   AS b ON b.id = l.book_id
JOIN members AS m ON m.id = l.member_id
WHERE l.returned_on IS NULL
ORDER BY l.due_on;

-- 2. Copies available on the shelf
SELECT b.title,
       b.copies,
       b.copies - COUNT(l.id) AS available
FROM books AS b
LEFT JOIN loans AS l ON l.book_id = b.id AND l.returned_on IS NULL
GROUP BY b.id
ORDER BY b.id;

Output

+-----------+--------+------------+
| title     | member | due_on     |
+-----------+--------+------------+
| Himu      | Sadia  | 2026-03-19 |
| Himu      | Tanvir | 2026-04-05 |
| Misir Ali | Rahim  | 2026-04-16 |
+-----------+--------+------------+
(3 rows)

+--------------------+--------+-----------+
| title              | copies | available |
+--------------------+--------+-----------+
| Himu               | 3      | 1         |
| Gitanjali          | 2      | 2         |
| Agnibina           | 1      | 1         |
| Amar Bondhu Rashed | 2      | 2         |
| Misir Ali          | 2      | 1         |
| Shesher Kobita     | 1      | 1         |
+--------------------+--------+-----------+
(6 rows)
  • Three loans have no return date, ordered by due date.
  • The second query puts the condition l.returned_on IS NULL inside the LEFT JOIN, not in WHERE. That keeps books with no open loans, so COUNT(l.id) is 0 for them.
  • Himu has 3 copies and 2 are out, so 1 is available.

3. Fines, Popularity and Members

-- 3. Overdue on 20 April 2026, with a fine of 5 taka per day late
SELECT m.name, b.title, l.due_on,
       CAST(julianday('2026-04-20') - julianday(l.due_on) AS INTEGER)     AS days_late,
       CAST(julianday('2026-04-20') - julianday(l.due_on) AS INTEGER) * 5 AS fine_taka
FROM loans AS l
JOIN books AS b   ON b.id = l.book_id
JOIN members AS m ON m.id = l.member_id
WHERE l.returned_on IS NULL AND l.due_on < '2026-04-20'
ORDER BY days_late DESC;

-- 4. Most borrowed authors
SELECT a.name AS author, COUNT(l.id) AS loans
FROM authors AS a
JOIN books AS b ON b.author_id = a.id
LEFT JOIN loans AS l ON l.book_id = b.id
GROUP BY a.id
ORDER BY loans DESC, author;

-- 5. Members who have never borrowed
SELECT name FROM members AS m
WHERE NOT EXISTS (SELECT 1 FROM loans AS l WHERE l.member_id = m.id);

-- 6. Each member's latest loan
SELECT name, title, borrowed_on
FROM (SELECT m.name, b.title, l.borrowed_on,
             ROW_NUMBER() OVER (PARTITION BY m.id ORDER BY l.borrowed_on DESC) AS rn
      FROM loans AS l JOIN members AS m ON m.id = l.member_id JOIN books AS b ON b.id = l.book_id)
WHERE rn = 1
ORDER BY name;

Output

+--------+-----------+------------+-----------+-----------+
| name   | title     | due_on     | days_late | fine_taka |
+--------+-----------+------------+-----------+-----------+
| Sadia  | Himu      | 2026-03-19 | 32        | 160       |
| Tanvir | Himu      | 2026-04-05 | 15        | 75        |
| Rahim  | Misir Ali | 2026-04-16 | 4         | 20        |
+--------+-----------+------------+-----------+-----------+
(3 rows)

+----------------------+-------+
| author               | loans |
+----------------------+-------+
| Humayun Ahmed        | 4     |
| Muhammed Zafar Iqbal | 2     |
| Rabindranath Tagore  | 1     |
| Kazi Nazrul Islam    | 0     |
+----------------------+-------+
(4 rows)

+------+
| name |
+------+
| Mim  |
+------+
(1 row)

+--------+--------------------+-------------+
| name   | title              | borrowed_on |
+--------+--------------------+-------------+
| Rahim  | Misir Ali          | 2026-04-02  |
| Sadia  | Amar Bondhu Rashed | 2026-03-20  |
| Tanvir | Amar Bondhu Rashed | 2026-04-04  |
+--------+--------------------+-------------+
(3 rows)
  • Overdue: on 20 April 2026, Sadia is 32 days late with Himu and owes 160 taka at 5 taka a day. In a live system, replace the fixed date with date('now').
  • Popular authors: LEFT JOIN loans keeps Kazi Nazrul Islam with 0 loans; an inner join would hide him.
  • Inactive members: NOT EXISTS finds Mim, who has never borrowed.
  • Latest loan: ROW_NUMBER per member, newest first, then keep row 1.

4. Constraints at Work

-- The CHECK constraints protect the data
INSERT INTO books VALUES (7,'Test Book',1,-2);                                  -- fails
INSERT INTO loans VALUES (8,1,4,'2026-04-10','2026-04-01',NULL);                -- fails

Output

Error: CHECK constraint failed: copies >= 0

Error: CHECK constraint failed: due_on > borrowed_on

Both inserts are rejected. Negative copies and a due date before the borrowing date can never reach the table, so later reports can trust the data.

Ideas to Extend the Project

  • Add a genres table and a monthly report of loans per genre with a pivot.
  • Write a trigger that refuses a loan when no copies are available.
  • Create a view overdue_loans so staff can see late books with one simple query.

Common Mistakes

  1. Putting the “open loan” filter in WHERE in the availability query, which drops books with no loans.
  2. Using an inner join for “most popular”, which hides authors with zero loans.
  3. Storing dates as “20/4/2026”. Comparisons such as due_on < '2026-04-20' only work with ISO dates.
  4. Calculating fines for returned books. Always check returned_on IS NULL first.

Practice Exercises

Exercise 1. How many loans did each member make, including members with none?

Show answer
SELECT m.name, COUNT(l.id) AS loans
FROM members AS m
LEFT JOIN loans AS l ON l.member_id = m.id
GROUP BY m.id
ORDER BY loans DESC, m.name;

Rahim 3, Sadia 2, Tanvir 2, Mim 0.

Exercise 2. Find loans that were returned late, with the number of days late.

Show answer
SELECT l.id, b.title,
       CAST(julianday(l.returned_on) - julianday(l.due_on) AS INTEGER) AS days_late
FROM loans AS l JOIN books AS b ON b.id = l.book_id
WHERE l.returned_on > l.due_on;

Only loan 2: Gitanjali was returned 6 days late.

Frequently Asked Questions

Why not store “available copies” as a column in books?

It can be done for speed, but then every loan and return must update it, and a mistake makes it wrong. Calculating it from loans always gives the true number. Large systems often store it and keep it correct with triggers.

Can a book have several authors?

In this design, no. To allow it, remove author_id from books and add a book_authors table with one row per book–author pair, a many-to-many relationship.

Summary

  • Good design (keys, NOT NULL, CHECK) keeps the data trustworthy.
  • Conditions inside a LEFT JOIN keep unmatched rows; conditions in WHERE remove them.
  • julianday differences turn dates into days for fines.
  • NOT EXISTS and ROW_NUMBER answer “never” and “latest” questions.

Next: SQL Self Join.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *