Digits
n Data
Netflix SQL Interview Question 10

First
Content
Watched

Find the first content watched by each user.

Schema

Table
Setup

Column NameTypeDescription
user_idintegerUser identifier.
content_idintegerWatched content identifier.
watch_datedateDate watched.

Sample Data

Input
Output

Sample Input: watching_activity
user_idcontent_idwatch_date
10112024-01-01
10122024-01-03
10232024-01-02
10242024-01-05
10322024-01-04
10312024-01-01
10432024-01-06
Expected Output
user_idcontent_id
1011
1023
1031
1043

SQL Editor

Run
Query

postgresql
Waiting for query

user_idcontent_id
1011
1023
1031
1043

Hints

Unlock
Clues

Hint 01: Window functions are perfect for first-row-per-group problems.
Hint 02: Use ROW_NUMBER() partitioned by user_id.
Hint 03: Keep rn = 1.

Solution

Locked
Answer

Solution is locked until you decide to reveal it. Try the editor first, then open this when you want the reference answer.

WITH ranked_activity AS (
  SELECT
    user_id,
    content_id,
    ROW_NUMBER() OVER (
      PARTITION BY user_id
      ORDER BY watch_date
    ) AS rn
  FROM watching_activity
)
SELECT
  user_id,
  content_id
FROM ranked_activity
WHERE rn = 1;

Explanation

Step By
Step

01

Rank every watch row inside its user_id group by watch_date.

02

Assign the earliest row rn = 1.

03

Select user_id and content_id from those first rows.

Related Questions

Keep
Solving