Two at a time
- O(n log n) · Hard
- Full plan
- SQL
- joins
- nulls
- comparisons
Problem
The librarian suspects that some members borrow a book while they still have another one at home. There's no rule against it, but she wants to know who, and with which books.
A member had a book at home on the day they borrowed another one if the first book went out on an earlier day and wasn't back yet: either it's still out, or it came back after that day. Returning one book and borrowing another on the same visit doesn't count.
Show the member, the title of the book they already had, the title of the one they borrowed, and the day they borrowed it, in that order.
What it has to return
These rows, in any order
| member | already_had | also_took | day |
|---|---|---|---|
| Ann | Three Winters | The Blue House | 2026-01-13 |
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.member, l.book_id,
l.borrowed, l.returned
FROM loans l
ORDER BY l.member, l.borrowed;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.