KatInterview

Gap Between a User's Two Latest Views of the Same Ad

SQL & DataModel answer
MediumModel answerSQL & Datasqlwindow-functionsrow-number

Last updated

Write one SQL query returning, per user and ad with at least two views, the newest and second-newest timestamps plus the gap between them in seconds.

Recent Ad Exposure Gaps

An ad platform logs each time an ad is shown to a user in a table:

impressions(ad_id INT, user_id INT, impression_ts TIMESTAMP)

A given (user_id, ad_id) pair can appear many times. All timestamps are in UTC.

Task

Write a single SQL query (standard SQL with window functions) that returns one row for every (user_id, ad_id) pair that has at least two impressions, with these columns:

  • user_id
  • ad_id
  • last_ts: the most recent impression timestamp
  • second_last_ts: the next most recent impression timestamp
  • diff_seconds: the number of seconds between last_ts and second_last_ts

Rank the rows inside each (user_id, ad_id) group with ROW_NUMBER() ordered by impression_ts DESC. Pairs with only one impression must not appear in the output.

Sample data (today is 2025-09-01)

ad_iduser_idimpression_ts
10112025-09-01 11:55:00
10112025-09-01 12:00:00
10112025-09-01 12:05:00
10122025-09-01 13:00:00
10122025-09-01 13:15:00
10212025-09-01 14:00:00

Expected result

  • (user 1, ad 101) gives diff_seconds = 300
  • (user 2, ad 101) gives diff_seconds = 900
  • (user 1, ad 102) is excluded because it has only one impression

What to cover in your answer

  • The query itself, and why you chose your ranking function.
  • How you drop single-impression groups.
  • How the seconds difference is written in at least one specific SQL dialect.
  • Edge cases: duplicate timestamps, NULL timestamps, time zones.

Hints

Hint 1

Partition by both user_id and ad_id, and order by impression_ts descending, so that row number 1 is the newest impression and row number 2 is the one before it.

Hint 2

You need the two timestamps side by side in one row. Either pivot rows 1 and 2 with conditional aggregation, or use LEAD over the same descending window to read the next-older timestamp directly.

Hint 3

Groups with a single impression produce no second row (or a NULL from LEAD), so filter on that. Also think about where NULL timestamps sort under DESC, and which date-difference function your dialect uses.