Querydrill

Level 5: Interview classics Exercise 125 of 161 Hard Previous and next row

Reactivated subscribers

An SQL exercise from Querydrill. Solve it with a SQL editor in your browser, checked on the rows it returns and again on changed data, and it is checked the moment you submit.

Try it yourself

The end date is the first day without the subscription, so a new subscription that starts on the previous end date is a plan change with no gap. A reactivation is a subscription whose start date is later than the end date of the same user's previous subscription. A user's subscriptions never overlap. Return the user_id, the start date of each reactivation, and the gap in days: that start date minus the previous end date.

subscriptions (10 rows)

iduser_idplanstart_dateend_date
11basic2025-01-102025-03-10
22pro2025-01-15NULL
33basic2025-01-202025-02-20
44pro2025-02-012025-04-01
53pro2025-03-15NULL
65basic2025-02-102025-03-10
76basic2025-03-01NULL
81pro2025-03-10NULL
97pro2025-03-202025-03-25
105basic2025-04-052025-05-05

Free, no account needed. PostgreSQL runs in your browser and your answer is checked again on changed data.

What this exercise teaches

LAG looks one subscription back for the same user. If that one ended before this one starts, the user was away and came back. A plan change on the same day has an end date equal to the next start date, so it is not a reactivation.

A hint if you get stuck

LAG(end_date) puts the previous subscription's end next to each row.

Background you need

Common mistakes on this exercise

  • Counts a plan change on the same day as a reactivation.
  • Measures the gap from the previous start date instead of the previous end date.

Each of these returns a result that looks plausible. The checker catches them because it runs your query on changed data as well.

Keep going on the practice page

Your first 8 exercises on Querydrill are free, with no account. The practice page has the full editor, timed mode and all the exercises in order. A free account shows 3 reference solutions a day; Pro unlocks every exercise, every solution, timed mode and the certificate.

Open this exercise

More practice on the same topic

More exercises in Interview classics