KatInterview

Predicting the Output of a Join + Aggregate + Window Query

SQL & DataModel answer
MediumModel answerSQL & Datasqljoinswindow-functions

Last 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:

  1. Which rows appear in the output, and in what order?
  2. What value does each column hold in each row?
  3. How does placing v.views >= 100 in the ON clause (rather than WHERE) change the answer?
  4. How are NULLs treated in the join, the aggregates, the partition, and the sort?
  5. What does RANK do 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.