Gap Between a User's Two Latest Views of the Same Ad
SQL & DataModel answerLast 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_idad_idlast_ts: the most recent impression timestampsecond_last_ts: the next most recent impression timestampdiff_seconds: the number of seconds betweenlast_tsandsecond_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_id | user_id | impression_ts |
|---|---|---|
| 101 | 1 | 2025-09-01 11:55:00 |
| 101 | 1 | 2025-09-01 12:00:00 |
| 101 | 1 | 2025-09-01 12:05:00 |
| 101 | 2 | 2025-09-01 13:00:00 |
| 101 | 2 | 2025-09-01 13:15:00 |
| 102 | 1 | 2025-09-01 14:00:00 |
Expected result
(user 1, ad 101)givesdiff_seconds = 300(user 2, ad 101)givesdiff_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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
For each (user_id, ad_id) only the two newest impressions matter. Number the rows from newest to oldest inside each group:
ROW_NUMBER() OVER (PARTITION BY user_id, ad_id ORDER BY impression_ts DESC)
Row 1 is the latest impression and row 2 is the one before it. Anything with a higher number is ignored. A group with no row 2 has fewer than two impressions and is dropped.
ROW_NUMBER is the right choice rather than RANK or DENSE_RANK. With ties on timestamp, RANK would give two rows rank 1 and nobody rank 2, which breaks the "second newest" logic. ROW_NUMBER always assigns a unique 1, 2, 3, ... sequence.
Query 1: rank, then pivot
WITH ranked AS (
SELECT user_id, ad_id, impression_ts,
ROW_NUMBER() OVER (
PARTITION BY user_id, ad_id
ORDER BY impression_ts DESC
) AS rn
FROM impressions
WHERE impression_ts IS NOT NULL
),
last_two AS (
SELECT user_id, ad_id,
MAX(CASE WHEN rn = 1 THEN impression_ts END) AS last_ts,
MAX(CASE WHEN rn = 2 THEN impression_ts END) AS second_last_ts
FROM ranked
WHERE rn <= 2
GROUP BY user_id, ad_id
HAVING COUNT(*) = 2
)
SELECT user_id, ad_id, last_ts, second_last_ts,
CAST(EXTRACT(EPOCH FROM (last_ts - second_last_ts)) AS BIGINT) AS diff_seconds
FROM last_two
ORDER BY user_id, ad_id;
Step by step:
rankednumbers every impression within its pair.last_twokeeps rows withrn <= 2and collapses them into one row per pair.MAX(CASE ...)picks out each timestamp.HAVING COUNT(*) = 2removes pairs that only had a row 1.- The outer query subtracts the two timestamps and converts to seconds.
Query 2: LEAD (shorter)
WITH w AS (
SELECT user_id, ad_id,
impression_ts AS last_ts,
LEAD(impression_ts) OVER (
PARTITION BY user_id, ad_id ORDER BY impression_ts DESC
) AS second_last_ts,
ROW_NUMBER() OVER (
PARTITION BY user_id, ad_id ORDER BY impression_ts DESC
) AS rn
FROM impressions
WHERE impression_ts IS NOT NULL
)
SELECT user_id, ad_id, last_ts, second_last_ts,
CAST(EXTRACT(EPOCH FROM (last_ts - second_last_ts)) AS BIGINT) AS diff_seconds
FROM w
WHERE rn = 1 AND second_last_ts IS NOT NULL;
With a descending order, LEAD returns the next-older timestamp. For the newest row (rn = 1) that is exactly the second-last impression. Single-impression groups get NULL and are filtered out. Both window functions share the same partition and order, so most engines sort only once.
Dialect-specific seconds difference
| Engine | Expression |
|---|---|
| PostgreSQL | EXTRACT(EPOCH FROM (last_ts - second_last_ts)) |
| BigQuery | TIMESTAMP_DIFF(last_ts, second_last_ts, SECOND) |
| MySQL | TIMESTAMPDIFF(SECOND, second_last_ts, last_ts) |
| Snowflake / SQL Server | DATEDIFF(second, second_last_ts, last_ts) |
| Spark SQL | unix_timestamp(last_ts) - unix_timestamp(second_last_ts) |
Note the argument order: some functions take (start, end), others (end, start). Getting it backwards gives negative values.
Result on the sample
| user_id | ad_id | last_ts | second_last_ts | diff_seconds |
|---|---|---|---|---|
| 1 | 101 | 2025-09-01 12:05:00 | 2025-09-01 12:00:00 | 300 |
| 2 | 101 | 2025-09-01 13:15:00 | 2025-09-01 13:00:00 | 900 |
(1, 102) has a single row, so it never gets rn = 2 and is excluded. The 11:55 impression for (1, 101) gets rn = 3 and is discarded.
Complexity
- Time: O(n log n), dominated by sorting within partitions. If the data is already clustered or indexed on
(user_id, ad_id, impression_ts), many engines can stream it without a full sort. - Space: O(n) for window buffers in the worst case. Output size is the number of qualifying pairs.
Edge cases and common mistakes
- Partitioning by only one key. Using just
user_idor justad_idmixes different ads or users into one ranking and gives wrong gaps. - Duplicate timestamps. Two impressions at the same instant take rows 1 and 2 in arbitrary order and yield
diff_seconds = 0. That is correct if every logged impression counts. If duplicates are logging artifacts, dedupe first withSELECT DISTINCT user_id, ad_id, impression_ts. If animpression_idcolumn existed, add it as a secondary sort key for determinism. Clarify the intent with the interviewer. - NULL timestamps. In PostgreSQL and Oracle,
DESCputs NULLs first, so a NULL would become row 1 and corrupt the result. Filterimpression_ts IS NOT NULLor useDESC NULLS LAST. - Time zones. The data is UTC, so differences are straightforward. With
TIMESTAMP WITH TIME ZONEor mixed sources, normalize to UTC first so DST changes do not distort gaps. - Fractional seconds.
EXTRACT(EPOCH ...)returns a decimal in PostgreSQL. Cast or floor it if an integer is required. - Using RANK or DENSE_RANK. Ties can produce no rank 2, breaking the pivot, as described above.
- Forgetting the single-impression filter. Without
HAVING COUNT(*) = 2orsecond_last_ts IS NOT NULL, pairs with one impression appear with NULL gaps.
Which version to present
Lead with the LEAD version if you are comfortable with it, because it is compact and easy to verify. Mention the ROW_NUMBER pivot as the form that matches the "rank, then take rows 1 and 2" framing and that works on engines or styles where you prefer explicit ranks. Either is correct on the sample and on all the edge cases above, provided NULLs are filtered and ties are discussed.