Library Loans in SQL: Popular Genres and Overdue Books

Intro to Databases · week 6 homework · SQLite

1. The questions, made measurable

  1. Which genres are borrowed most? Count loans per books.genre, highest first.
  2. Which members currently have overdue books? Loans where returned_on IS NULL and due_on is before today.

Schema:

2. Check the data first

CheckQueryWhy
Loans pointing to missing booksSELECT COUNT(*) FROM loans l LEFT JOIN books b ON b.book_id = l.book_id WHERE b.book_id IS NULL;Broken links disappear from joins and change counts
Missing genresSELECT COUNT(*) FROM books WHERE genre IS NULL OR genre = '';They would form a blank group
Date formatSELECT due_on FROM loans LIMIT 5;SQLite compares dates as text, so they must be YYYY-MM-DD

3. How the tables connect

text
members.member_id ──< loans.member_id
books.book_id     ──< loans.book_id

One member has many loans; one book has many loans. loans is the bridge, so both questions start from loans and join out to the other tables.

4. Query 1 — Most-borrowed genres

sql
SELECT
  b.genre,                    -- the group we want
  COUNT(*) AS loan_count      -- how many loans in each group
FROM loans AS l
JOIN books AS b
  ON b.book_id = l.book_id    -- match each loan to its book
GROUP BY b.genre              -- one row per genre
ORDER BY loan_count DESC;     -- most borrowed first

Line by line:

5. Query 2 — Members with overdue books right now

sql
SELECT
  m.member_id,
  m.name,
  b.title,
  l.due_on,
  CAST(julianday('now') - julianday(l.due_on) AS INTEGER) AS days_overdue
FROM loans AS l
JOIN members AS m ON m.member_id = l.member_id
JOIN books   AS b ON b.book_id   = l.book_id
WHERE l.returned_on IS NULL            -- still out
  AND l.due_on < date('now')           -- past the due date
ORDER BY days_overdue DESC;

Line by line:

6. What the output should look like

Example shape only — results depend on your data. [run to check]

genreloan_count
[run to check][run to check]
member_idnametitledue_ondays_overdue
[run to check][run to check][run to check][run to check][run to check]

7. Common errors

8. Practice tasks

  1. List members who have never borrowed a book. Hint: LEFT JOIN loans and keep rows where l.loan_id IS NULL.
  2. Show the average loan length in days per genre for returned books only.

Next step: run both queries and paste the first few rows; I'll help you check them. Which part was hardest — the joins or GROUP BY?

Sample output · ChatterMate.Ai Prompt Library · fictional data — your result will differ.