Step 5: Design the database
Data must survive a restart, so design the tables for a database: books, members and loans. The loan table links the other two with foreign keys (REFERENCES). A loan with returned_on IS NULL is still open. Run the schema and the sample data, then the query for current loans:
Now ask the questions the application needs. Available books are those with no open loan, and a LEFT JOIN counts loans even for books never borrowed:
The Java rules map onto SQL: "already on loan" is an open loan exists for this ISBN, and the two-book limit is SELECT COUNT(*) FROM loans WHERE member_id = ? AND returned_on IS NULL. In Java you would run these with JDBC using prepared statements (placeholders ?) to prevent SQL injection.
In the loans table, what marks a loan as still open?
Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.
Tip: use the left and right arrow keys to move between lessons.