Querydrill

Level 5: Interview classics Exercise 122 of 161 Hard Product analytics

Rolling 7-day active users

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

For every day that has events, return the day, as a date, and the number of different users with an event in the 7 days ending on that day (that day and the 6 days before it).

events (first 12 of 38 rows)

iduser_ideventevent_time
11visit2025-03-01 09:00:00
21signup2025-03-01 09:05:00
31purchase2025-03-01 09:20:00
42visit2025-03-01 10:00:00
51visit2025-03-01 15:00:00
61visit2025-03-02 10:00:00
73visit2025-03-02 12:00:00
83visit2025-03-02 12:40:00
91visit2025-03-03 08:00:00
101purchase2025-03-03 08:10:00
113signup2025-03-03 09:00:00
122visit2025-03-03 11:00:00

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

What this exercise teaches

Each day is joined to all events from 6 days earlier up to that day, and the users are counted once. Summing the daily numbers over a window would count the same user on every day they were active.

A hint if you get stuck

A window function cannot count distinct values. Join each day to the events of its 7 days instead.

Background you need

Common mistakes on this exercise

  • Adds up daily counts: a user active on three days is counted three times, and 6 rows back is not 6 days back when a day is missing.
  • Day minus 7 up to the day itself is 8 days.

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