The library forgets
- O(n²) · Very hard
- Full plan
- SQL
- changing data
- subqueries
Problem
This library doesn't keep a history of what each member has read. For each book it holds on to a single loan, the latest one, which is enough to know who has the book or who had it last. The earlier ones get deleted.
A book's latest loan is the one that went out last, going by its date in borrowed. The loan number won't tell you: loan 8 was entered after loan 7, but it went out in December. The same book never goes out twice on the same day. And a book with a single loan keeps it, returned or not.
Write the delete. It's graded by looking at which loans are left.
What it has to return
After your code, this query runs
SELECT id, book_id, member FROM loans;These rows, in any order
| id | book_id | member |
|---|---|---|
| 3 | 1 | Dylan |
| 4 | 4 | Ann |
| 5 | 6 | Hannah |
| 6 | 3 | Ann |
| 7 | 7 | Luke |
| 8 | 2 | Brian |
This is what comes out with the data in the practice database this challenge uses. The column names don’t count, so name yours however you like: what counts is how many there are and the order they come in. Besides this one, the challenge has hidden tests with other data that are revealed when you submit your solution.
You start with this
SQL
DELETE FROM loans
WHERE returned IS NOT NULL;It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.
More O(n²) challenges
- The next rung upSQL · window functions · subqueries
- The register, day by daySQL · window functions · grouping · conditionals
- The third stampSQL · window functions · joins · dates
- The week of the 4thSQL · dates · grouping · strings
- What went out todaySQL · changing data · subqueries · nulls
- Which day do we close?SQL · dates · grouping · conditionals