Full answer
text
books(id, isbn UNIQUE, title, author)
book_copies(id, book_id FK, barcode UNIQUE, status)
members(id, name, joined_at)
loans(id, copy_id FK, member_id FK, borrowed_at, due_at, returned_at)
CREATE UNIQUE INDEX one_open_loan_per_copy ON loans(copy_id) WHERE returned_at IS NULL;
fines(id, loan_id FK, amount_minor, paid_at)Common queries:
- Available copies of a title: copies with no open loan.
- Overdue loans:
returned_at IS NULL AND due_at < :today. - A member's history: loans by member_id, newest first.
The partial unique index is the key rule; it works in SQLite and PostgreSQL. Storing fines as rows when a book comes back fixes the amount according to the rules in force at that time, rather than recomputing later.
Key points
- Separate titles from copies
- Loans per copy with open and returned state
- Partial unique index for one open loan
- Fines recorded as rows
Common mistakes
- A single available flag that drifts from loan data
- Treating a title as one lendable item
Follow-ups
- How would you add reservations for titles?
- How would you limit members to five open loans?
Tips
- Show the partial unique index