New year, new page
- O(n log n) · Hard
- Full plan
- SQL
- sets
- sorting
- nulls
Problem
The library's front desk keeps a notebook where every loan and every return gets its own line. A fresh page was started with the new year, and it's time to make a clean copy of it: everything that has moved since January 1, 2026.
Show the day, what happened (out or back), and the book's title, in that order. A book that went out in December and came back in January leaves only its back line on this page, and a book that's still out doesn't have a back line yet.
Sort by day. Within a day the returns go first, because a book has to come back before it can go out again, and then the loans. If there's still a tie, sort by title.
What it has to return
These rows, in this order
| day | movement | title |
|---|---|---|
| 2026-01-02 | out | The Lighthouse |
| 2026-01-03 | out | The Blue House |
| 2026-01-04 | back | Maps of Salt |
| 2026-01-05 | back | The Blue House |
| 2026-01-08 | out | Long Night |
| 2026-01-09 | back | The Lighthouse |
| 2026-01-10 | out | The Lighthouse |
| 2026-01-10 | out | Three Winters |
| 2026-01-12 | out | The Train South |
| 2026-01-13 | out | The Blue House |
| 2026-01-14 | back | Three Winters |
| 2026-01-15 | back | Long Night |
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
SELECT l.borrowed AS day,
'out' AS movement,
b.title
FROM loans l
JOIN books b
ON l.book_id = b.id
ORDER BY day;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 log n) challenges
- News to DenverSQL · subqueries · joins
- Not on the rosterSQL · subqueries · joins · grouping
- Often ordered togetherSQL · joins · grouping
- One student, one voteSQL · subqueries · grouping
- Report cards read acrossSQL · joins · grouping · conditionals
- Spent nothing, still on the listSQL · joins · nulls · grouping