Longest Gap Between Library Visits
Problem
Table: `library_visit`
| Column Name | Type |
|---|---|
| patron_id | int |
| visit_day | date |
There is no primary key, but for any patron all `visit_day` values are distinct. Each row records that `patron_id` visited the library on `visit_day`.
For each patron, report the **longest gap in days** between two of their visits. For the gap that follows a patron's most recent visit, treat the period as ending on the reference date **2026-01-01**. Output `patron_id` and the gap as an integer aliased `longest_gap`, ordered by `patron_id`.
Tables
Example rows — the live problem includes the full dataset.
| patron_id | visit_day |
|---|---|
| 1 | 2025-12-01 |
| 1 | 2025-12-05 |
| 1 | 2025-12-20 |
Expected output
Your answer should return 2 rows with the columns patron_id, longest_gap.
Starter code (SQL)
SELECT *
FROM library_visit;Solve this SQL question free
Write SQL and run it instantly in your browser — even on your phone. No signup needed to try.
Solution & explanation
Create a free account to unlock the optimal solution, a step-by-step explanation, and the hidden test cases that grade your answer.
Sign up free to unlock