← Back to SQL, page 21

sql-0401 · Easy fresher

Design tables for a library that lends books, tracking copies, loans, due dates and fines.

Separate the title (books) from physical copies (book_copies), and record loans per copy with borrowed_at, due_at and returned_at. A partial unique index on loans(copy_id) WHERE returned_at IS NULL ensures a copy is lent to only one member at a time. Fines are derived from overdue days or recorded as charges when the book is returned.

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