// free study notes

SQL window function interview questions

A staple of senior-level screens: ranking without collapsing rows, running totals, LAG for period-over-period change, and frame traps.

12 questions
  • 1 easy
  • 8 medium
  • 3 hard
Practice mode: all topics, shuffled

What this page covers

  • 12 questions on window functions, tagged easy, medium or hard, each with a worked answer in runnable SQL.
  • One schema throughout. The answers use the small shop schema shown here. Dialect-specific examples name the engine they are written for, and the few extra tables a question needs, such as subscribers or logins, are introduced where they appear.
  • Practice mode. To test yourself first, press Hide answers: each answer waits behind a Show answer button. The practice mode link deals a shuffled deck from every topic.
The shop schema
customers(customer_id, name, city, signup_date)
orders(order_id, customer_id, order_date, status, total)
order_items(order_id, product_id, quantity, unit_price)
products(product_id, name, category, price)
employees(employee_id, name, manager_id, department, salary, hired_on)

The questions

What does AVG(salary) OVER () do, and how is it different from GROUP BY?

Easy

An empty OVER computes the aggregate over every row of the result and attaches it to each row, without collapsing rows the way GROUP BY does.

SELECT name, department, salary,
AVG(salary) OVER () AS company_avg
FROM employees;

GROUP BY would collapse the table to one row (or one per department); the window version returns every employee with the company average alongside, so salary - AVG(salary) OVER () gives each person's distance from the average in one pass. Without the window you need a subquery or a join back to an aggregate. The window is computed after WHERE, so filtering to one department changes the average too.

What is the difference between ROW_NUMBER, RANK and DENSE_RANK?

中

All three number rows within a partition in ORDER BY order. ROW_NUMBER gives every row a distinct number, breaking ties arbitrarily. RANK gives tied rows the same rank and skips the following numbers. DENSE_RANK gives tied rows the same rank and skips nothing.

SELECT name, department, salary,
ROW_NUMBER() OVER w AS rn,
RANK()       OVER w AS rnk,
DENSE_RANK() OVER w AS drnk
FROM employees
WINDOW w AS (PARTITION BY department ORDER BY salary DESC);

With salaries 2000, 2000, 1500 the outputs are 1, 2, 3 for ROW_NUMBER; 1, 1, 3 for RANK; 1, 1, 2 for DENSE_RANK. Say which you would use: exactly n rows per group needs ROW_NUMBER (with a tiebreaker in the ORDER BY so the result is repeatable), a leaderboard with ties wants RANK, and the nth distinct value wants DENSE_RANK. The named WINDOW clause works on PostgreSQL, MySQL 8, SQLite and SQL Server 2022+; older SQL Server needs the OVER (...) written out each time.

Return the highest-paid employee in each department.

中

Rank within each department partition, then filter the ranking outside the subquery. Window functions cannot appear in WHERE because WHERE runs first.

SELECT department, name, salary
FROM (
SELECT name, department, salary,
ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rn
FROM employees
) ranked
WHERE rn = 1;

The follow-up to expect: what if two people tie for the top salary? ROW_NUMBER returns one arbitrarily; RANK with WHERE rnk = 1 returns both. Choosing deliberately is the difference between a memorized pattern and an understood one.

Compute a running total of order revenue by date.

中

OVER with ORDER BY: once a window has an ORDER BY, the default frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, from the partition start to the current row and its peers, so the sum accumulates.

SELECT order_date,
SUM(total) OVER (ORDER BY order_date) AS running_total
FROM (
SELECT order_date, SUM(total) AS total
FROM orders
GROUP BY order_date
) daily;

Two details worth stating: ties on order_date all share the same running total because peers are in the same frame (use ORDER BY order_date, order_id for a strict order), and pre-aggregating to one row per day keeps the window small and the intent clear.

What do LAG and LEAD do? Show month-over-month revenue change.

中

LAG fetches a value from a previous row of the partition, LEAD from a following one, both offset by a count with a default for the edges.

SELECT month, revenue,
LAG(revenue) OVER (ORDER BY month) AS prev_month,
revenue - LAG(revenue) OVER (ORDER BY month) AS change
FROM (
SELECT DATE_TRUNC('month', order_date) AS month, SUM(total) AS revenue
FROM orders
GROUP BY 1
) monthly;

The first row returns NULL for prev_month, so change is NULL there, not zero, which is usually what a report should show. LAG(revenue, 1, 0) supplies an explicit default if you do want zero. A gotcha worth raising: LAG looks at the previous row, not the previous calendar month, so a month with no orders is silently skipped and the next change spans two months. Join to a month calendar first if gaps are possible. The query uses PostgreSQL's DATE_TRUNC; the aggregation questions show the other engines' spelling.

Compute each employee's share of their department salary bill.

中

Two window expressions over the same partition: the department total and the row-level division.

SELECT name, department, salary,
SUM(salary) OVER (PARTITION BY department) AS dept_total,
salary * 100.0 / SUM(salary) OVER (PARTITION BY department) AS pct_of_dept
FROM employees;

With GROUP BY you would lose the per-employee rows and need a join back to the aggregates. The window version does it in one pass, which is the standard answer to share-of-total questions.

Compute a 3-day moving average of daily revenue.

Hard

Restrict the frame with ROWS BETWEEN. The default frame runs from the partition start; a moving window needs explicit bounds.

SELECT order_date,
AVG(total) OVER (
ORDER BY order_date
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
) AS moving_avg_3day
FROM (
SELECT order_date, SUM(total) AS total
FROM orders
GROUP BY order_date
) daily;

Note the edge behavior: the first two days average fewer than three values because the frame is truncated at the partition start. ROWS counts physical rows, so a day with no orders has no row and the window quietly stretches over four calendar days. PostgreSQL 11+ can express a true calendar window with RANGE BETWEEN INTERVAL '2 days' PRECEDING AND CURRENT ROW.

Split employees into four salary quartiles with NTILE.

中

NTILE(n) distributes partition rows as evenly as possible into n buckets, numbered 1 to n in the window order.

SELECT name, salary,
NTILE(4) OVER (ORDER BY salary DESC) AS quartile
FROM employees;

The follow-up is usually uneven divisions: with 10 rows and 4 tiles, the earlier tiles get the extra rows (3, 3, 2, 2). NTILE also ignores ties, so two people with the same salary can land in different quartiles. When that matters, PERCENT_RANK or CUME_DIST give each row a value between 0 and 1 that ties share, and you bucket on that instead.

Gaps and islands: find each streak of consecutive active days per user.

Hard

Number each user's active days in date order, then subtract that row number (as days) from the date. Consecutive days produce the same result, so that value labels an island.

-- PostgreSQL; logins(user_id, login_date) is not in the shop schema:
WITH daily AS (
SELECT DISTINCT user_id, login_date::date AS day
FROM logins
),
grouped AS (
SELECT user_id, day,
day - ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY day) * INTERVAL '1 day' AS grp
FROM daily
)
SELECT user_id, MIN(day) AS streak_start, MAX(day) AS streak_end, COUNT(*) AS days
FROM grouped
GROUP BY user_id, grp
ORDER BY user_id, streak_start;

Worked through: logins on Jan 1, 2, 3 and 5 get row numbers 1, 2, 3, 4, so date minus row number is Dec 31, Dec 31, Dec 31 and Jan 1. Two islands: Jan 1 to 3 (3 days) and Jan 5 (1 day). The SELECT DISTINCT matters, because two logins on one day would otherwise get two row numbers and break the streak. The same trick finds gaps in invoice numbers or runs of failed jobs.

Why does putting a window function in WHERE fail, and what do you do instead?

中

WHERE runs before window functions are evaluated, so the window result does not exist yet. The fix is to compute the window in a subquery or CTE and filter outside it.

SELECT * FROM (
SELECT name, department, salary,
RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS rnk
FROM employees
) ranked
WHERE rnk = 1;

Snowflake, BigQuery, DuckDB, Databricks and Teradata support QUALIFY, which filters on window results directly: QUALIFY RANK() OVER (PARTITION BY department ORDER BY salary DESC) = 1. PostgreSQL, SQL Server, MySQL, SQLite and Oracle do not, so the subquery or CTE form is the one to write in an interview unless you know the target engine.

What does FIRST_VALUE do, and what is the LAST_VALUE trap?

中

FIRST_VALUE and LAST_VALUE return an expression from the first and last row of the frame. The trap: with an ORDER BY, the default frame ends at the current row (plus any rows tied with it), so LAST_VALUE returns the current row or its last tied peer, not the partition's last row.

SELECT name, department, salary,
FIRST_VALUE(name) OVER w AS top_earner,
LAST_VALUE(name)  OVER w AS last_row_only,      -- usually wrong
LAST_VALUE(name)  OVER (w ROWS BETWEEN UNBOUNDED PRECEDING
                           AND UNBOUNDED FOLLOWING) AS lowest_earner
FROM employees
WINDOW w AS (PARTITION BY department ORDER BY salary DESC);

With salaries 2000, 2000 and 1500, last_row_only returns the second 2000 earner for both of the first two rows and the 1500 earner for the third. FIRST_VALUE escapes the trap only because the default frame starts at UNBOUNDED PRECEDING. When LAST_VALUE misbehaves, the fix is the frame: extend it to UNBOUNDED FOLLOWING, or use FIRST_VALUE with the ORDER BY reversed. A window that already has an ORDER BY can add a frame but cannot get a second ORDER BY, which is why the frame is appended to w here.

Delete duplicate rows, keeping the latest one per natural key.

Hard

Number duplicates by recency with ROW_NUMBER partitioned on the natural key, then delete where the number is greater than one.

WITH ranked AS (
SELECT ctid AS row_id,
ROW_NUMBER() OVER (
   PARTITION BY email ORDER BY updated_at DESC
) AS rn
FROM customers
)
DELETE FROM customers
WHERE ctid IN (SELECT row_id FROM ranked WHERE rn > 1);

ctid is PostgreSQL's physical row address, used here because true duplicates may have no distinguishing key; it is stable only within the statement, so never store it. Elsewhere, use the primary key; SQL Server can even delete through the CTE directly (WITH ranked AS (...) DELETE FROM ranked WHERE rn > 1). ORDER BY updated_at DESC with rn > 1 keeps the newest row, and if two rows share an updated_at the survivor is arbitrary unless you add a tiebreaker. Run the SELECT first to preview what will be deleted, then add a UNIQUE constraint on email so the duplicates cannot come back.

Window functions interview FAQ

Which window function questions come up most in interviews?

ROW_NUMBER versus RANK versus DENSE_RANK, top-n per group, running totals, LAG for period-over-period change, and deleting duplicates with ROW_NUMBER. All are here with worked SQL.

Do the answers explain OVER (PARTITION BY ...) versus OVER ()?

Yes. The first question contrasts an empty OVER, which aggregates over the whole table while keeping every row, with the partitioned form used for per-group shares.

Is there a question about window frame boundaries?

Two: a moving average with ROWS BETWEEN 2 PRECEDING AND CURRENT ROW, and the LAST_VALUE trap, where the default frame stops at the current row and its peers instead of the end of the partition.

Why does my window function fail in WHERE?

Because WHERE runs before window functions are evaluated. One answer shows the portable subquery workaround and the QUALIFY clause that Snowflake, BigQuery, DuckDB and Databricks offer.

Other topics

// from study notes to daily tool

Now write some SQL against a real database

SQLly is a native SQL workbench for macOS, Windows and Linux: IntelliSense that knows your schema, a formatter, guardrails for risky queries, and every engine in one app.