The SQL round

Part of the free LogicWiz Data Engineering course, Module 18: Interview rounds. The SQL and Python run in the app, on real Postgres and real Python in the browser.

It is the SQL round. The interviewer shares an editor with SwiftKart's tables and says: "Find every run of consecutive days on which we beat our revenue target. You have fifteen minutes." You know SQL. So did most of the people who failed this round. They did not see the shape of the question fast enough, or their query broke on a tie nobody mentioned.

You'll learn to

  • Recognise the nine classic SQL question shapes from the wording
  • Build each answer step by step with CTEs and window functions
  • Guard every answer against ties, NULLs, repeated timestamps and missing days

Learn

How the round runs

The round is usually 45 to 60 minutes: two to four questions on one small schema, such as orders, users and events. You type in a shared editor. Often you cannot run anything, so the interviewer watches how you get to the answer.

A steady routine beats speed:

  1. Say the grain of the answer: "one row per category".
  2. Ask about edge cases: ties, NULLs, cancelled orders, days with no data.
  3. Name the pattern, and build it in CTEs, one step each.
  4. Check it on two or three rows, out loud.

The ten problems below are graded on hidden data. A tie, a NULL or a new day is added, so a query that only fits the rows you can see fails, exactly as it would when a careful interviewer pushes.

Recognise the shape

The question saysReach forWatch out for
"second highest", "top 3 per group"DENSERANK() or ROWNUMBER() in a CTE, filter outside itties: which function matches the wording?
"latest", "current", "most recent per key"ROWNUMBER() OVER (PARTITION BY key ORDER BY ts DESC, tiebreaker) = 1two rows with the same timestamp
"compared with the day before"LAG(value) OVER (ORDER BY day)LAG is the previous row, not the previous day
"running", "cumulative", "so far"SUM(x) OVER (ORDER BY ... ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)the default frame lumps equal sort values together
"consecutive days", "streak"day minus ROWNUMBER() labels each islandrepeated days: dedup first
"session", "30 minutes of inactivity"flag a gap with LAG, then a running SUM of the flagsis exactly 30 minutes a new session?
"cohort", "retention", "came back"first activity per user, then join later activity backusers with no activity at all
"bought A but never B"EXISTS and NOT EXISTS (an anti-join)NOT IN with a NULL returns nothing
"one column per status"COUNT() FILTER (WHERE ...)NULL where 0 is meant

Read the left column like a phrase book: the words in the question tell you which pattern to reach for. Most SQL rounds are these nine shapes in different clothes. Module 2 taught each one; this round drills them against hidden data.

Build one answer: streaks

Take the question from the scene. Stripped down, it asks for runs of consecutive days. The trick is one subtraction.

Put one user's active days in date order and number them: 1, 2, 3, 4, 5. Now subtract each row's number from its date.

Inside a run of consecutive days, the date and the row number both go up by one, so the difference stays the same. When a day is skipped, the date jumps by two while the row number moves by one, so the difference changes.

That constant difference is a label for the run. A run is often called an island, and the pattern gaps and islands. Group by the label, and each group is one streak.

Five active days become two streaks

Five active days, 1, 2, 3, 5 and 6 June, are numbered in date order; subtracting the row number from the date gives 31 May for the first three days and 1 June for the last two, which labels two islands.

  1. The active days. One user was active on 1, 2, 3, 5 and 6 June. (A day that appears twice is removed first, with DISTINCT.)

  2. Number them in date order. ROW_NUMBER() gives 1, 2, 3, 4, 5.

  3. Subtract the row number from the date. 1 June minus 1 day is 31 May. So is 2 June minus 2, and 3 June minus 3. Then a day is skipped, and the answer changes: 5 June minus 4 is 1 June.

  4. Group by that difference. Each value labels one run of consecutive days. Island A is 1 to 3 June, 3 days. Island B is 5 to 6 June, 2 days. MIN, MAX and COUNT per group give the start, the end and the length.

Each box is one day. Watch the second line of each box: it is the same for days that follow each other.

Gaps and islands on a login table

WITH days AS (
  SELECT DISTINCT user_id, day
  FROM logins
), labelled AS (
  SELECT user_id, day,
         day - (ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY day))::int AS island
  FROM days
)
SELECT user_id, MIN(day) AS streak_start, MAX(day) AS streak_end, COUNT(*) AS days
FROM labelled
GROUP BY user_id, island
ORDER BY user_id, streak_start;

Three CTE steps, the same three as the picture: distinct days, label each day, group by the label. DISTINCT comes first because user 1 logged in twice on 2 June, and a repeated day would break the subtraction. In Postgres a date minus an integer is a date.

How Postgres runs the streaks query

The plan tree from EXPLAIN for the streaks query: a sequential scan, a hash aggregate for the DISTINCT, a sort on user and day, the window aggregate that numbers the rows, a hash aggregate on the island label and a final sort.

Read it from the bottom up: that is the order Postgres works in. It comes from EXPLAIN (COSTS OFF) on the query above. A window needs its rows sorted by the PARTITION BY and ORDER BY keys, so on a big table the sort under WindowAgg is the step that spills past work_mem. That is your answer to the follow-up "how does this scale?"

Keep the latest row, with a tie-breaker

WITH ranked AS (
  SELECT order_id, payment_id, status, paid_ts,
         ROW_NUMBER() OVER (
           PARTITION BY order_id
           ORDER BY paid_ts DESC, payment_id DESC
         ) AS rn
  FROM payments
)
SELECT order_id, payment_id, status, paid_ts
FROM ranked
WHERE rn = 1
  AND order_id IN (1012, 1033);

The second most common shape. Order 1012 failed and then succeeded, so its latest payment is the captured one. payment_id DESC decides when two rows share a timestamp, so the answer never changes between runs.

Interviewers grade four things. Did you ask about ties and NULLs? Is the query right on the edge rows? Can you explain each CTE? Is it readable? Saying "I will use DENSE_RANK because tied products should share a place" earns more than silent typing. If you finish early, raise the edge case yourself: "a day with no orders has no row, so LAG would skip it; I could join a calendar table."

The trap: three ways a correct-looking query fails on hidden data. RANK and ROW_NUMBER answer differently from DENSE_RANK when values tie. A ROW_NUMBER with no tie-breaker picks a random winner between equal timestamps. And a running total ordered by a column with repeated values (two orders in the same second) gives both rows the same total, because the default frame includes every row that sorts equal. Name a tie-breaker, and write the frame: ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW.

Remember: grain, edge cases, pattern, check. Say each one out loud before you type.

Next is the Python round: the same kind of problem, with dicts and loops and no SQL engine to lean on.

In one line

Name the shape of the question first, build it in small CTE steps, then guard it against ties, NULLs, repeated timestamps and missing days.

Interview corner

How do you find the second-highest value in each group when values can tie?

Rank inside each group with DENSE_RANK() OVER (PARTITION BY grp ORDER BY value DESC) in a CTE and keep rank 2. DENSE_RANK gives ties the same number without gaps, so rank 2 is the second-highest distinct value even when two rows share the top. The filter goes outside the CTE because a window function cannot sit in WHERE.

How do you find streaks of consecutive days?

Deduplicate to one row per user and day, then subtract ROW_NUMBER() (ordered by day, per user) from the date. Inside a run of consecutive days that difference is constant, so grouping by it gives one group per streak, with MIN, MAX and COUNT for start, end and length. It is called gaps and islands.

What is the difference between ROWS and RANGE in a window frame?

ROWS counts physical rows; RANGE groups rows with equal sort values as one step. A running total with ORDER BY order_ts uses RANGE by default, so two orders in the same second get the same total. I sort by a unique key and write ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW to be explicit.

How would you sessionise clickstream events in SQL?

Per user, take the previous event time with LAG, flag an event as a new session when there is no previous event or the gap is more than the timeout, then a running SUM of the flags is the session number. Group by user and session number to get start, end and event count. I would confirm with the interviewer whether exactly 30 minutes counts as the same session.