DEV Community

NostrobeAI
NostrobeAI

Posted on

SQL Window Function Interview Questions: Ranking, Frames and Ties

Window functions perform calculations across related rows without removing individual rows from the result. They are useful for ranking employees within a department, calculating running totals and comparing neighbouring events. Interviewers often start with this distinction before moving on to ties, window frames and duplicate rows, where seemingly correct SQL can answer a different question.

PARTITION BY vs GROUP BY

GROUP BY collapses rows into one result per group. PARTITION BY divides the rows seen by a window function into groups while preserving every input row. If the question asks for each employee alongside their department's average salary, a window function is a natural fit:

SELECT
  department,
  salary,
  AVG(salary) OVER (PARTITION BY department) AS department_average
FROM employees;
Enter fullscreen mode Exit fullscreen mode

Each employee row remains visible. Using GROUP BY department instead would return one row per department, losing individual salaries.

In an interview, explain what each output row should represent before choosing between the two approaches.

ROW_NUMBER vs RANK vs DENSE_RANK

These functions differ in how they handle ties. ROW_NUMBER assigns a unique sequence, ordering tied rows arbitrarily unless the window order includes an additional tie-breaker. RANK assigns tied rows the same rank and leaves a gap afterwards: 1, 2, 2, 4. DENSE_RANK assigns the same rank without leaving a gap: 1, 2, 2, 3.

The right choice depends on how the question requires ties to be counted.

For the Nth-highest distinct salary, use DENSE_RANK in a subquery and filter on the requested rank. Duplicate salaries receive the same rank:

SELECT salary
FROM (
  SELECT
    salary,
    DENSE_RANK() OVER (ORDER BY salary DESC) AS salary_rank
  FROM employees
) ranked_salaries
WHERE salary_rank = 3;
Enter fullscreen mode Exit fullscreen mode

Here, 3 is the requested N. If the interviewer wants the third row after sorting, counting duplicate salaries as separate positions, a different ranking rule is needed. Clarify this distinction before writing the filter.

LAG and LEAD instead of a self-join

LAG reads a value from the preceding row in the window order, while LEAD reads from the following row. Both allow you to compare neighbouring events without joining a table to itself.

For example, order each customer's orders by creation time and retrieve the timestamp of their previous order:

SELECT
  customer_id,
  created_at,
  LAG(created_at) OVER (
    PARTITION BY customer_id
    ORDER BY created_at
  ) AS previous_order_at
FROM orders;
Enter fullscreen mode Exit fullscreen mode

The first row for each customer has no previous timestamp, so its LAG value is null. The same pattern can compare consecutive transactions or identify gaps between events.

If timestamps can be identical, consider which additional ordering column would make “previous” unambiguous. The table shown here does not provide one.

ROWS vs RANGE and the 7-day rolling average

A window frame determines which rows around the current row contribute to a calculation. ROWS counts physical rows. For example, ROWS BETWEEN 2 PRECEDING AND CURRENT ROW includes the current row and the two preceding rows.

RANGE uses the values in the ORDER BY expression, including rows tied on that value together. When ordering values are duplicated, RANGE can therefore produce a different running total from ROWS.

For a seven-row average over daily sales, use an explicit ROWS frame:

SELECT
  date,
  value,
  AVG(value) OVER (
    ORDER BY date
    ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
  ) AS rolling_average
FROM daily_sales;
Enter fullscreen mode Exit fullscreen mode

The frame includes the current row and up to six preceding rows. It represents seven calendar days only when there is one row for every date.

If dates are missing, six preceding rows can span more than seven days. To account for this, join the sales data to a generated date series before applying the frame. The method for generating that series varies by database.

First order per customer

To return one first order per customer, rank each customer's orders by timestamp and retain the row numbered one:

SELECT customer_id, created_at
FROM (
  SELECT
    customer_id,
    created_at,
    ROW_NUMBER() OVER (
      PARTITION BY customer_id
      ORDER BY created_at
    ) AS order_number
  FROM orders
) numbered_orders
WHERE order_number = 1;
Enter fullscreen mode Exit fullscreen mode

A common alternative is to find MIN(created_at) for each customer and join that timestamp back to orders. However, if two orders share the earliest timestamp, both will match, duplicating the customer in the result.

ROW_NUMBER() = 1 returns one row. If the identity of that row matters when timestamps tie, the window order needs an additional tie-breaker column. None is shown in this table.

Consecutive events: gaps and islands

A gaps-and-islands query groups consecutive dates into runs. Number each user's login dates in order, then subtract the row number from each date. The resulting group key remains constant within each consecutive run:

WITH numbered_logins AS (
  SELECT
    user_id,
    login_date,
    ROW_NUMBER() OVER (
      PARTITION BY user_id
      ORDER BY login_date
    ) AS rn
  FROM logins
), grouped_logins AS (
  SELECT
    user_id,
    login_date,
    login_date - CAST(rn AS int) AS island_key
  FROM numbered_logins
)
SELECT user_id, island_key, COUNT(*) AS run_length
FROM grouped_logins
GROUP BY user_id, island_key
HAVING COUNT(*) >= 3;
Enter fullscreen mode Exit fullscreen mode

This query retains runs of at least three dates. The date-minus-integer syntax varies by database engine. PostgreSQL, for example, accepts login_date - CAST(rn AS int) for a date value.

The same approach generalises to other minimum run lengths by changing the HAVING condition. As with ranking, duplicate dates or ambiguous event ordering require an explicit decision about what counts as a separate event.

The full set, from joins to practical problems, is on NostrobeAI's SQL interview questions page.

Top comments (0)