Predicting the Output of a Join + Aggregate + Window Query
SQL & DataModel answerLast updated
Read a multi-clause SQL query against two small tables and state exactly which rows come back, with each column value, traced stage by stage.
You are handed two small tables and a single query. Without executing anything, describe the result precisely.
users videos
user_id | country video_id | user_id | views
1 | US 10 | 1 | 100
2 | US 11 | 1 | 300
3 | UK 12 | 2 | 400
4 | NULL 13 | 2 | NULL
6 | US 14 | 3 | 50
15 | 5 | 70
16 | 4 | 200
17 | 6 | 150
SELECT u.user_id,
u.country,
COUNT(v.video_id) AS n_videos,
SUM(v.views) AS total_views,
RANK() OVER (PARTITION BY u.country
ORDER BY SUM(v.views) DESC) AS rnk
FROM users u
LEFT JOIN videos v
ON u.user_id = v.user_id AND v.views >= 100
GROUP BY u.user_id, u.country
HAVING COUNT(*) >= 1
ORDER BY u.country, rnk, u.user_id;
Assume PostgreSQL semantics. Answer:
- Which rows appear in the output, and in what order?
- What value does each column hold in each row?
- How does placing
v.views >= 100in theONclause (rather thanWHERE) change the answer? - How are NULLs treated in the join, the aggregates, the partition, and the sort?
- What does
RANKdo with ties, and where do other dialects behave differently?
State your assumptions explicitly and call out the edge cases a careful engineer would flag.
Hints
Hint 1
Recite the logical evaluation order of SQL clauses before touching the data — FROM, WHERE, GROUP BY, aggregates, HAVING, window functions, SELECT/DISTINCT, ORDER BY/LIMIT — and then follow it strictly.
Hint 2
For a LEFT JOIN, a predicate in the ON clause prunes which right-side rows match; putting the same predicate in WHERE would remove the NULL-extended left rows and silently make it an inner join.
Hint 3
COUNT(*) counts rows including NULL-extended ones, but COUNT(col) skips NULLs, and SUM over only NULLs is NULL rather than 0 — these three facts decide which groups survive HAVING.
Hint 4
RANK leaves gaps after ties; the partition key NULL forms its own group; ascending sort puts NULLs last in Postgres but first in MySQL/SQL Server.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
A strong answer states the logical evaluation order up front, then materializes each intermediate result in turn. It ends with the final table, the assumptions, and the edge cases.
Evaluation order. Though written SELECT-first, SQL evaluates: FROM/JOIN → WHERE → GROUP BY → aggregates → HAVING → window functions → SELECT/DISTINCT → ORDER BY → LIMIT. Every clause consumes the previous clause's output, so applying a filter at the wrong stage is the main source of errors.
Step 1 — LEFT JOIN with a predicate in ON. The predicate v.views >= 100 lives in the ON clause, so it restricts which videos count as matches but never removes a user. A user with no qualifying video is still kept as a single NULL-extended row.
- User 1 matches videos 10 (100) and 11 (300): two rows.
- User 2 matches video 12 (400). Video 13 has
views = NULL, andNULL >= 100is UNKNOWN, which the ON predicate treats as not matching: one row. - User 3's only video 14 has 50 views, which fails: user 3 is preserved as one NULL-extended row.
- User 4 matches video 16 (200); user 6 matches video 17 (150).
- Video 15 belongs to user 5, who is absent from
users, so it is dropped (the non-preserved side).
Step 2 — GROUP BY and aggregates. Grouping by (user_id, country) gives:
| user_id | country | COUNT(*) | COUNT(v.video_id) | SUM(v.views) |
|---|---|---|---|---|
| 1 | US | 2 | 2 | 400 |
| 2 | US | 1 | 1 | 400 |
| 3 | UK | 1 | 0 | NULL |
| 4 | NULL | 1 | 1 | 200 |
| 6 | US | 1 | 1 | 150 |
COUNT(*) counts the NULL-extended row for user 3, while COUNT(v.video_id) skips the NULL and yields 0. SUM over an all-NULL set returns NULL, not 0.
Step 3 — HAVING. COUNT(*) >= 1 holds for every group, so user 3 survives. Had it been COUNT(v.video_id) >= 1, user 3 would be dropped — a classic probe.
Step 4 — Window function. RANK() runs over rows after HAVING, partitioned by country, ordered by SUM(v.views) DESC. The NULL country forms its own partition.
- US: 400, 400, 150 → ranks 1, 1, 3.
RANKleaves a gap after a tie;DENSE_RANKwould give 1,1,2, andROW_NUMBERwould break the tie nondeterministically. - UK: user 3 alone → rank 1.
- NULL partition: user 4 alone → rank 1.
Step 5 — ORDER BY. ORDER BY u.country, rnk, u.user_id sorts ascending. Postgres places NULLs last on ascending sort, so the NULL-country row goes last; MySQL and SQL Server put NULLs first, changing the row order but not the set.
Final result (PostgreSQL):
| user_id | country | n_videos | total_views | rnk |
|---|---|---|---|---|
| 3 | UK | 0 | NULL | 1 |
| 1 | US | 2 | 400 | 1 |
| 2 | US | 1 | 400 | 1 |
| 6 | US | 1 | 150 | 3 |
| 4 | NULL | 1 | 200 | 1 |
Five rows. User 5 is absent (no matching user), and video 13 contributes nothing.
ON vs WHERE. Moving v.views >= 100 into WHERE would evaluate after the join: user 3's NULL-extended row would fail the predicate and be removed, silently converting the LEFT JOIN into an inner join. This distinction is the most commonly probed nuance.
Edge cases to raise. Join fan-out: duplicate keys on both sides multiply rows and inflate SUM/COUNT(*) — COUNT(DISTINCT …) masks duplicates but SUM does not. Three-valued logic: NULL = NULL is UNKNOWN, so NULL join keys never match; NOT IN against a subquery containing NULL yields no rows. Grouping and partitioning treat all NULLs as one group. AVG divides by the non-null count. Ties in ORDER BY are otherwise nondeterministic without a tiebreaker. Default window frames apply: ORDER BY inside OVER defaults to RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, including peer rows.
Cost. Hash join: O(|users| + |videos|) with a hash table on the smaller side. Hash aggregation: O(n) time, O(groups) space. Window: sort within partitions, O(g log g) over g groups. Final ORDER BY: another O(g log g) unless it reuses the window's ordering.
Verifying in pandas (matching Postgres semantics):
import pandas as pd
users = pd.DataFrame({"user_id":[1,2,3,4,6], "country":["US","US","UK",None,"US"]})
videos = pd.DataFrame({"video_id":[10,11,12,13,14,15,16,17],
"user_id":[1,1,2,2,3,5,4,6],
"views":[100,300,400,None,50,70,200,150]})
v = videos[videos["views"].fillna(-1) >= 100] # ON predicate
m = users.merge(v, on="user_id", how="left")
g = m.groupby(["user_id","country"], dropna=False).agg(
n_videos=("video_id","count"),
total_views=("views","sum")).reset_index()
g["rnk"] = g.groupby("country")["total_views"].rank(method="min", ascending=False)
print(g.sort_values(["country","rnk","user_id"], na_position="last"))
This reproduces five rows with the ranks above. Stating assumptions — dialect, NULL ordering, tie semantics — and offering this sanity check signals rigor.