Past due
- O(n²) · Very hard
- Full plan
- SQL
- dates
- nulls
- joins
Problem
The library lends for 3 days, and until today nobody has kept track of who went over. The librarian wants the whole list: the loans that came back late and the ones still out and overdue.
The days late are the days the book was out minus the 3 days of the loan period, counted up to the day it came back or, if it hasn't, up to today, January 15, 2026. A book that comes back, or is due, right on the third day is on time and stays off the list.
Show the title, the member, the return date (empty if the book is still out), and the days late, in that order. The most days late go first, and ties go by title. You can write today as '2026-01-15' or as DATE('now').
What it has to return
These rows, in this order
| title | member | returned | days_late |
|---|---|---|---|
| Maps of Salt | Brian | 2026-01-04 | 12 |
| Long Night | Luke | 2026-01-15 | 4 |
| The Lighthouse | Ann | 2026-01-09 | 4 |
| The Lighthouse | Dylan | NULL | 2 |
| Three Winters | Ann | 2026-01-14 | 1 |
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 b.title, l.member, l.returned
FROM loans l
JOIN books b
ON l.book_id = b.id
WHERE l.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
- Starting at the bottomSQL · changing data · subqueries
- The library forgetsSQL · changing data · subqueries
- 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