January off the shelf
- O(n²) · Very hard
- Full plan
- SQL
- dates
- nulls
- grouping
Problem
The librarian wants to know which books barely touch the shelf: how many days of this January has each one spent out?
The days are counted by subtracting dates: a book that goes out on the 3rd and comes back on the 5th was out 2 days. One that hasn't come back counts up to today, January 15, 2026. If a book went out more than once, its days add up. And nothing from before January 1 counts: for a loan that started in December, only the days from the 1st on.
Show the title and the days, in that order, for every book: one that hasn't been out in January gets a 0. The most days out 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 | days |
|---|---|
| The Lighthouse | 12 |
| Long Night | 7 |
| The Blue House | 4 |
| Three Winters | 4 |
| Maps of Salt | 3 |
| The Train South | 3 |
| Loose Leaves | 0 |
| Short Stories | 0 |
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 book_id, borrowed, returned,
JULIANDAY(returned)
- JULIANDAY(borrowed) AS days
FROM loans;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
- Lighthouse, TheSQL · strings · conditionals · sorting
- One raise, not twoSQL · changing data · conditionals
- Out of every 100 in payrollSQL · window functions · decimals
- Paige is leavingSQL · changing data · subqueries
- Past dueSQL · dates · nulls · joins
- Starting at the bottomSQL · changing data · subqueries