SteelReed

Search

Search posts, questions…

4. Database & SQL

Databases: the library exercise, fixing the brief and reviewing the schema before querying

The library exercise in real working order: fix the brief, turn business rules into constraints, emulate a partial unique index on MySQL, make returns idempotent, review schemas and SQL an AI wrote.

17 Nov 20268 min readMid

–

1. The problem

The spec says "a copy can only be borrowed by one person". The first schema adds UNIQUE(book_id): tests pass, but in week two no copy can be borrowed again. The fix moves the check into Java; two librarians click 40 ms apart and copy B0001 ends up in 2 open loans.

2. Key idea

The spec talks in time ("at any moment"), while a simple constraint applies to every row forever. A copy has many loans over time (1-n), only one open at a time. Translate each sentence of the spec into a question the schema must answer and a constraint the database keeps; anything that won't translate goes back as a question.

Problem in the spec Fix
Asks "unreturned books" with no return-date column returned_at DATETIME NULL (NULL = not returned)
UNIQUE(book_id) at most one open loan per copy
"Book 1-1 Book_Invoice" Book 1-n Loan
Loan and due dates nullable, penalties can go negative NOT NULL, CHECK (penalty >= 0), CHECK (date_out < due_date)
Tool Use when Don't use when
NOT NULL, CHECK required values, fixed domains lists that change: lookup table + FK
Plain UNIQUE unique forever (card numbers) unique "at one moment"
Partial unique at most one open loan per copy rules spanning several tables
Application checks early, friendly errors as the only line of defense

3. In SQL

SQL
-- MySQL: a generated column that only has a value while the loan is open
CREATE TABLE loan (
  invoice_no   INT AUTO_INCREMENT PRIMARY KEY,
  book_id      VARCHAR(5) NOT NULL,
  date_out     DATETIME   NOT NULL,
  due_date     DATETIME   NOT NULL,
  returned_at  DATETIME   NULL,
  penalty      DECIMAL(10,2) NOT NULL DEFAULT 0 CHECK (penalty >= 0),
  open_book_id VARCHAR(5) AS (CASE WHEN returned_at IS NULL THEN book_id END) STORED,
  CONSTRAINT uq_loan_one_open_per_book UNIQUE (open_book_id),
  CONSTRAINT chk_loan_dates CHECK (date_out < due_date)
);
-- PostgreSQL: CREATE UNIQUE INDEX ON loan (book_id) WHERE returned_at IS NULL;
 
-- Returning a book: compare-and-set, a second run updates 0 rows
UPDATE loan SET returned_at = NOW(),
       penalty = GREATEST(DATEDIFF(NOW(), due_date), 0) * 0.5
WHERE invoice_no = ? AND returned_at IS NULL;

Spring reports error 1062 as DuplicateKeyException; catch it to return "this book is on loan" instead of a 500. For returns, check the row count from executeUpdate(). Go, Node.js and C# use the same DDL and the same unique-violation handling.

Common traps in library queries
  • Overdue: always include returned_at IS NULL, or long-returned books count as overdue.
  • "Each member with their loan count": LEFT JOIN + COUNT(l.invoice_no) so members with no loans show 0.
  • Dates: compare bare columns with half-open ranges (date_out >= CURRENT_DATE AND date_out < CURRENT_DATE + INTERVAL 1 DAY), with "today" in the business time zone.
  • Deletes: default RESTRICT foreign keys for books and members with history; soft delete when history must stay.
  • Natural keys (the code on the book's label) change with the business; use a surrogate primary key and make the code UNIQUE.

4. Working with AI

Hand to AI: DDL from an agreed ERD, draft queries, sample data relative to NOW() covering: returned on time, returned late, overdue, borrowed today, never borrowed.

Check yourself in AI-written code:

  • Every business question in the spec has a column that answers it.
  • "At one moment" rules are partial unique, not plain UNIQUE.
  • Loan and due dates are NOT NULL; penalties have CHECK (penalty >= 0).
  • Every overdue condition includes returned_at IS NULL.
  • The return statement has AND returned_at IS NULL and checks the row count.

5. Exercises

Exercise 1: Review the AI's loan table

The AI says "two people borrowing the same copy is blocked by a DB constraint". Find the bugs, name a test that proves it, fix it.

SQL
CREATE TABLE loan (
  invoice_no  INT AUTO_INCREMENT PRIMARY KEY,
  card_no     VARCHAR(5) NOT NULL,
  book_id     VARCHAR(5) NOT NULL UNIQUE,
  date_out    DATETIME,
  due_date    DATETIME,
  returned_at DATETIME NULL,
  penalty     DECIMAL(10,3) DEFAULT 0
);
Solution 1
  • book_id ... UNIQUE does stop two simultaneous borrowers, but also every later loan. Test: borrow B0001, return it, borrow again; the second loan fails with 1062. Fix: open_book_id + UNIQUE (MySQL) or a partial unique index (PostgreSQL).
  • Nullable date_out, due_date: a loan with no due date is never overdue. Add NOT NULL and CHECK (date_out < due_date).
  • penalty lacks NOT NULL and CHECK (penalty >= 0).
  • Missing foreign keys to member and book, and the column for the staff member who issued the loan.

Exercise 2: Read a book-return incident

Member M0002 complains: loan 1003 was returned on time last week, and now shows a 3.0 penalty with today as the return date. The log has two "return" commands for loan 1003; the second came from a queue-replay job 6 days later. The code loads the loan into Java, sets returnedAt and penalty, then saves. Diagnose it, say what to do in 15 minutes, fix the root cause.

Solution 2
  • Diagnosis: returning isn't idempotent. Java read-modify-write doesn't check whether the loan is closed, so the replay overwrote the real return date and charged 6 days × 0.5 = 3.0.
  • 15 minutes: fix loan 1003 by hand from the first log entry, pause the replay job, look for other loans overwritten the same way.
  • Root fix: a single UPDATE ... WHERE invoice_no = ? AND returned_at IS NULL as in section 3; a second run updates 0 rows and the app reports "already returned".

Summary

  • Check the schema can answer every business question before writing queries.
  • "Only one at a time" is a partial unique, not a plain UNIQUE.
  • MySQL emulates a partial unique with a generated column + UNIQUE.
  • DB constraints stop races; application checks only give early errors.
  • Returning a book is a compare-and-set: a second run changes nothing.

Further reading: Indexes and query performance.

Practice interview questions on this topic

All Data Modeling & Scaling questions →All SQL & Query Tuning questions →

Loading comments…