Skip to the content

January off the shelf

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

titledays
The Lighthouse12
Long Night7
The Blue House4
Three Winters4
Maps of Salt3
The Train South3
Loose Leaves0
Short Stories0

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;
Solve this challenge

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

See all challenges →