# 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:**

- `members(member_id, name, joined_on)`
- `books(book_id, title, genre)`
- `loans(loan_id, book_id, member_id, loaned_on, due_on, returned_on)` — `returned_on` is NULL if not returned

## 2. Check the data first

| Check | Query | Why |
| --- | --- | --- |
| Loans pointing to missing books | `SELECT 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 genres | `SELECT COUNT(*) FROM books WHERE genre IS NULL OR genre = '';` | They would form a blank group |
| Date format | `SELECT 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:**

- `FROM loans AS l` — start from every loan; `l` is a short nickname.
- `JOIN books AS b ON …` — attach the book row to each loan, so we know its genre.
- `GROUP BY b.genre` — collapse all loans of the same genre into one row.
- `COUNT(*)` — count the loans inside each group.
- `ORDER BY … DESC` — sort from biggest to smallest.

## 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:**

- Two joins: one to get the member's name, one to get the book title.
- `returned_on IS NULL` — use `IS NULL`, never `= NULL` (that is never true in SQL).
- `date('now')` — today's date in SQLite. In MySQL use `CURDATE()`; in PostgreSQL `CURRENT_DATE`.
- `julianday(...)` — turns dates into day numbers so you can subtract them.

## 6. What the output should look like

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

| genre | loan_count |
| --- | --- |
| [run to check] | [run to check] |

| member_id | name | title | due_on | days_overdue |
| --- | --- | --- | --- | --- |
| [run to check] | [run to check] | [run to check] | [run to check] | [run to check] |

## 7. Common errors

- **"ambiguous column name: book_id"** → both tables have `book_id`; write `l.book_id` or `b.book_id`.
- **Counts too high** → you joined `members` in Query 1 for no reason and a duplicate member row multiplied loans. Only join what you need.
- **No overdue rows** → check the date format is `YYYY-MM-DD`; `'5/3/2026'` will not compare correctly.
- **Grouping error in other databases** → every non-aggregated column in `SELECT` must be in `GROUP BY`.

## 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?
