Library database design and queries
Design a normalised library database from scratch and answer 20 real questions with SQL.
What you'll learn
- ◆ER modelling and normalisation (1NF–3NF)
- ◆Primary and foreign keys, constraints
- ◆JOINs, GROUP BY, subqueries
What you'll build
- ✓ER diagram
- ✓Tables with constraints and sample data
- ✓20 business queries
- ✓Views for common reports
Step-by-step guide
- 1
Draw the ER diagram
Entities: Book, Author, BookAuthor (many-to-many), Member, Copy, Loan. Use dbdiagram.io or draw.io.
- 2
Create tables
CREATE TABLE with PRIMARY KEY, FOREIGN KEY ... REFERENCES, NOT NULL, UNIQUE (isbn) and CHECK (fine >= 0).
- 3
Insert sample data
At least 50 books, 20 members and 100 loans so the queries return interesting results.
- 4
Basic queries
Books by an author, members with overdue books (due_date < CURRENT_DATE AND returned_at IS NULL).
- 5
Aggregates
Top 5 most borrowed books (GROUP BY, ORDER BY COUNT(*) DESC LIMIT 5); members who never borrowed (LEFT JOIN ... IS NULL).
- 6
Window functions
Rank members by loans per month with RANK() OVER (PARTITION BY month ORDER BY loans DESC).
- 7
Views and indexes
CREATE VIEW overdue_loans; add an index on loans(member_id, due_date) and compare EXPLAIN output.
🚀 Make it stand out
- +A trigger that calculates fines on return
- +Stored procedure to issue a book
- +Connect a small web UI