Skip to main content

From an events table with user_id and event_date, compute daily active users and a 7-day moving average of that number. For example, if two different users have events on 1 November, the daily active users for that day is 2, even if one of them has five events.

Coding rounds · Intermediate 2

Short answer

First aggregate: SELECT event_date, COUNT(DISTINCT user_id) AS dau FROM events GROUP BY event_date. Then, over that result, take AVG(dau) OVER (ORDER BY event_date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW). The frame counts rows, so it is 7 days only when every date has a row; a calendar table fills gaps. Cost is one GROUP BY and one sort.

Deeper answer

First clarify the definitions. Ask what counts as active, which timezone defines a day, and whether event_date is a date or a timestamp that needs a cast. Ask whether days with no events exist and should count as zero.

Use two steps. In a CTE called daily, run SELECT event_date, COUNT(DISTINCT user_id) AS dau FROM events GROUP BY event_date. DISTINCT matters because one user can have many events in a day. In the outer query, select event_date, dau and AVG(dau) OVER (ORDER BY event_date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS avg_7d. The frame counts rows, not days, so if a date is absent the window reaches back more than a week. To fix that, build a calendar of dates, with generate_series in Postgres, LEFT JOIN daily to it and use COALESCE(dau, 0).

Note that this is an average of daily counts. It is not weekly active users, which needs COUNT(DISTINCT user_id) across the 7 days. Test a user with several events in one day and a day with no events.

What a strong answer covers

Answer it out loud in the mock interview about 3 min

Follow-ups to expect

Common mistakes

Learn it

SQL for engineers

Practice Coding rounds questions

More on this topic

Today's AI turns are used

Lessons, roadmaps, videos, practice cards and the code playground stay free with your account, with no limit.