Weekly Top Dialers and Share of French Video Participants
SQL & DataModel answerLast updated
Write two SQL queries on a call-log table: rank the ten users who placed the most calls in the past week, and compute the share of yesterday's French users who joined a video call.
A messaging app stores one row per call in a table named calls:
| call_id | caller_id | receiver_id | call_start_time | country | call_type |
|---|---|---|---|---|---|
| 1 | 101 | 202 | 2023-10-10 09:05:00 | France | video |
| 2 | 103 | 204 | 2023-10-10 10:15:00 | India | voice |
| 3 | 101 | 105 | 2023-10-09 22:30:00 | France | video |
| 4 | 106 | 107 | 2023-10-03 05:45:00 | Brazil | video |
| 5 | 108 | 109 | 2023-10-10 13:20:00 | France | voice |
call_start_time is a timestamp, country is the country in which the call took place, and call_type is either video or voice.
The product team wants two answers from this table.
Task 1. Return the 10 users who started the most calls (as caller_id) during the last 7 days, together with their call counts.
Task 2. Compute the percentage of active users in France who took part in a video call yesterday.
Before you write any SQL, state the assumptions you are making. In particular, address:
- How you define the "last 7 days" window and whether today is included.
- How you break ties at the 10th position.
- What "active user" means, and whether a user who only received a call counts.
- How you avoid integer division and division by zero.
Provide your queries, walk through the sample data (assume today is 2023-10-11), and mention any edge cases you would raise with the interviewer. A pandas version is a welcome bonus.
Hints
Hint 1
Use a half-open time range (`>= start AND < end`) rather than `BETWEEN` on a timestamp, so rows late in the final day are not lost or double counted.
Hint 2
For Task 1, filter to the window, `GROUP BY caller_id`, `COUNT(*)`, then order by the count descending with `caller_id` as a deterministic tie-breaker before applying `LIMIT 10`.
Hint 3
For Task 2, a user can be on either end of a call. Stack caller and receiver into one `user_id` column (`UNION ALL`), then use `COUNT(DISTINCT user_id)` for the denominator and `COUNT(DISTINCT CASE WHEN call_type = 'video' THEN user_id END)` for the numerator.
Hint 4
Multiply by `100.0` to force decimal arithmetic and wrap the denominator in `NULLIF(..., 0)` so a day with no French activity returns NULL rather than an error.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
What is being tested
Two short queries, but most of the value lies in how you handle the ambiguities: time windows, ties, the definition of "active", and safe percentage arithmetic. Say your assumptions aloud before writing code.
Task 1: Top 10 call initiators, last 7 days
Assumption. "Last 7 days" means the seven complete days before today: [CURRENT_DATE - 7 days, CURRENT_DATE). If partial data for today should count, move the upper bound to CURRENT_DATE + 1 day. Use a half-open range instead of BETWEEN, because BETWEEN on timestamps either drops late-day rows or includes midnight of the next day.
SELECT caller_id, COUNT(*) AS calls_initiated
FROM calls
WHERE call_start_time >= CURRENT_DATE - INTERVAL '7 days'
AND call_start_time < CURRENT_DATE
GROUP BY caller_id
ORDER BY calls_initiated DESC, caller_id
LIMIT 10;
Ties. LIMIT 10 cuts arbitrarily through a tie at rank 10, and the caller_id tie-breaker only makes that cut deterministic. If everyone tied at the boundary should be included, rank first:
WITH counts AS (
SELECT caller_id, COUNT(*) AS calls_initiated
FROM calls
WHERE call_start_time >= CURRENT_DATE - INTERVAL '7 days'
AND call_start_time < CURRENT_DATE
GROUP BY caller_id
),
ranked AS (
SELECT *, RANK() OVER (ORDER BY calls_initiated DESC) AS rnk
FROM counts
)
SELECT caller_id, calls_initiated
FROM ranked
WHERE rnk <= 10
ORDER BY calls_initiated DESC, caller_id;
Sample data (today = 2023-10-11). The window is 10-04 to 10-10. Call 4 (10-03) is excluded. Result: 101 -> 2, 103 -> 1, 108 -> 1.
Task 2: Percentage of active French users on video yesterday
Definitions to state:
- Active user: anyone who took part, as caller or receiver, in a call with
country = 'France'yesterday. - Video user: an active user with at least one
videocall yesterday, in either role. - Result:
100 * distinct video users / distinct active users.
Note that country here belongs to the call, not the user. With a real users table you would join to get each user's home country.
Approach. Unpivot each call into two participant rows, then count distinct users overall and distinct users with a video call, in one pass via conditional aggregation.
WITH participants AS (
SELECT caller_id AS user_id, call_type
FROM calls
WHERE country = 'France'
AND call_start_time >= CURRENT_DATE - INTERVAL '1 day'
AND call_start_time < CURRENT_DATE
UNION ALL
SELECT receiver_id AS user_id, call_type
FROM calls
WHERE country = 'France'
AND call_start_time >= CURRENT_DATE - INTERVAL '1 day'
AND call_start_time < CURRENT_DATE
)
SELECT
COUNT(DISTINCT user_id) AS active_users,
COUNT(DISTINCT CASE WHEN call_type = 'video' THEN user_id END) AS video_users,
ROUND(
100.0 * COUNT(DISTINCT CASE WHEN call_type = 'video' THEN user_id END)
/ NULLIF(COUNT(DISTINCT user_id), 0),
2) AS pct_video_users
FROM participants;
Why it works:
COUNT(DISTINCT ...)counts a user once regardless of how many calls they made.- The
CASEyieldsNULLfor voice rows, andCOUNTignoresNULL, so only users with at least one video call reach the numerator. A user with both voice and video calls is correctly a video user. 100.0forces decimal division;NULLIFavoids a divide-by-zero error.
Sample data (today = 2023-10-11). Yesterday's French calls are call 1 (101 and 202, video) and call 5 (108 and 109, voice). Call 3 falls on 10-09 and is excluded. Active = {101, 202, 108, 109} = 4, video = {101, 202} = 2, so the result is 50.00%.
If "active" means callers only, drop the receiver branch: active = {101, 108}, video = {101}, still 50%. Whichever you pick, state it.
Complexity and performance
- Task 1: one filtered scan, O(n), a hash aggregate over u distinct callers, and a top-k heap for
LIMIT, roughly O(u log 10). - Task 2: a scan over yesterday's French rows doubled by the unpivot, with O(u) memory for distinct counting.
- An index on
call_start_time, or a composite(country, call_start_time), turns scans into range scans. Date partitioning allows partition pruning.
Edge cases and common mistakes
- Using
BETWEENon timestamps, or comparing a timestamp to a date with=. - Counting only callers in Task 2 without saying so, or counting receivers twice because of a join instead of
DISTINCT. - Integer division producing 0 instead of 50.
- Time zones: if timestamps are stored in UTC, "yesterday in France" should use
AT TIME ZONE 'Europe/Paris'. - Duplicate
call_idrows: useCOUNT(DISTINCT call_id)in Task 1. - Dirty values such as
'Video'or'france': normalize withLOWER(). - A day with no French activity: the result is
NULL, not an error.
Pandas equivalent
import pandas as pd
def top_callers(calls, today, k=10):
end = today.normalize()
start = end - pd.Timedelta(days=7)
w = calls[(calls.call_start_time >= start) & (calls.call_start_time < end)]
return (w.groupby("caller_id").size().reset_index(name="calls_initiated")
.sort_values(["calls_initiated", "caller_id"], ascending=[False, True])
.head(k))
def pct_french_video_users(calls, today):
end = today.normalize()
start = end - pd.Timedelta(days=1)
y = calls[(calls.country == "France") &
(calls.call_start_time >= start) & (calls.call_start_time < end)]
parts = pd.concat([
y[["caller_id", "call_type"]].rename(columns={"caller_id": "user_id"}),
y[["receiver_id", "call_type"]].rename(columns={"receiver_id": "user_id"}),
])
active = parts.user_id.nunique()
if active == 0:
return None
video = parts.loc[parts.call_type == "video", "user_id"].nunique()
return round(100.0 * video / active, 2)
Both versions use the same definitions, window logic, and tie-breaking as the SQL, so they produce the same results.