๐ช Window Functions #1
Window functions compute a value for each row by looking at a group of related rows, without collapsing those rows into one. They answer questions like "what is each employee's rank in their department?" or "how does each salary compare with the department average?", and they are among the most asked topics in data engineering interviews.
This is the first of three tutorials on windows. Here you will learn ranking functions and aggregates over a window. The next two cover LEAD and LAG, and window frames.
1. Sample Data
This tutorial uses the employees view from the introduction:
CREATE OR REPLACE TEMP VIEW employees AS
SELECT * FROM VALUES
(1, 'Asha', 'Engineering', 95000, DATE'2019-03-15', NULL, 'Bengaluru'),
(2, 'Ben', 'Engineering', 82000, DATE'2020-07-01', 1, 'Pune'),
(3, 'Chen', 'Sales', 60000, DATE'2021-01-10', 1, 'Mumbai'),
(4, 'Divya', 'Sales', 65000, DATE'2018-11-23', 3, 'Mumbai'),
(5, 'Elena', 'Marketing', 58000, DATE'2022-05-30', 1, NULL),
(6, 'Farid', 'Engineering', 82000, DATE'2023-02-14', 2, 'Bengaluru'),
(7, 'Grace', NULL, 45000, DATE'2024-01-08', NULL, 'Delhi')
AS employees(emp_id, name, dept, salary, hire_date, manager_id, city)
Keep an eye on Ben and Farid: both earn 82000 in Engineering. That tie is what makes the ranking functions behave differently.
2. Window Functions vs GROUP BY
GROUP BY turns each group into one row. If you want the average salary per department, you get one row per department and lose the individual employees:
SELECT dept, AVG(salary) AS dept_avg
FROM employees
GROUP BY dept
ORDER BY dept
+-----------+-----------------+
|dept |dept_avg |
+-----------+-----------------+
|NULL |45000.0 |
|Engineering|86333.33333333333|
|Marketing |58000.0 |
|Sales |62500.0 |
+-----------+-----------------+
A window function computes the same average but keeps every row. Each employee gets the average of their own department next to their own salary:
SELECT name,
dept,
salary,
AVG(salary) OVER (PARTITION BY dept) AS dept_avg
FROM employees
ORDER BY dept, salary DESC
+-----+-----------+------+-----------------+
|name |dept |salary|dept_avg |
+-----+-----------+------+-----------------+
|Grace|NULL |45000 |45000.0 |
|Asha |Engineering|95000 |86333.33333333333|
|Ben |Engineering|82000 |86333.33333333333|
|Farid|Engineering|82000 |86333.33333333333|
|Elena|Marketing |58000 |58000.0 |
|Divya|Sales |65000 |62500.0 |
|Chen |Sales |60000 |62500.0 |
+-----+-----------+------+-----------------+
The OVER (...) part is what turns AVG into a window function. PARTITION BY dept says "compute this separately for each department", much like GROUP BY dept, but the rows stay as they are.
GROUP BY | Window function | |
|---|---|---|
| Rows in the result | One per group | One per input row |
| Can show row-level columns next to the result | No | Yes |
| Typical use | Totals, counts per group | Rankings, comparisons with the group, running totals |
Notice Grace: her dept is NULL, and all NULL departments form their own partition. Her dept_avg is simply her own salary.
3. The Shape of a Window
Every window function follows this pattern:
-- Syntax
function_name(args) OVER (
PARTITION BY columns -- optional: split rows into groups
ORDER BY columns -- optional for aggregates, required for ranking
frame -- optional: which rows around the current row to use
)
PARTITION BYsplits the rows into independent groups. Leave it out and the whole table is one group.ORDER BYsorts the rows inside each partition. Ranking functions need it, because "first" only makes sense in some order.- Frame (
ROWS BETWEEN ...) narrows the rows used for each calculation. It is covered in Window Frames.
The ORDER BY inside OVER only controls the window calculation. It does not sort the final result, so you still need an ORDER BY at the end of the query if you care about output order.
4. ROW_NUMBER, RANK and DENSE_RANK
These three functions number the rows of each partition. They differ only in how they treat ties:
SELECT name,
dept,
salary,
ROW_NUMBER() OVER (PARTITION BY dept ORDER BY salary DESC) AS row_number,
RANK() OVER (PARTITION BY dept ORDER BY salary DESC) AS rank,
DENSE_RANK() OVER (PARTITION BY dept ORDER BY salary DESC) AS dense_rank
FROM employees
WHERE dept = 'Engineering'
ORDER BY salary DESC, name
+-----+-----------+------+----------+----+----------+
|name |dept |salary|row_number|rank|dense_rank|
+-----+-----------+------+----------+----+----------+
|Asha |Engineering|95000 |1 |1 |1 |
|Ben |Engineering|82000 |2 |2 |2 |
|Farid|Engineering|82000 |3 |2 |2 |
+-----+-----------+------+----------+----+----------+
Ben and Farid both earn 82000:
| Function | Ben and Farid get | Next value after the tie | Rule |
|---|---|---|---|
ROW_NUMBER() | 2 and 3 | (none here) | Always unique: 1, 2, 3, 4... |
RANK() | 2 and 2 | 4 | Ties share a rank, then the numbering skips |
DENSE_RANK() | 2 and 2 | 3 | Ties share a rank, no gaps |
There is no fourth Engineering employee here, so you cannot see the gap yet. Section 5 ranks the whole table, where the gap shows up.
Common mistake: With a tie,
ROW_NUMBER()gives 2 to one of the tied rows and 3 to the other, and which one gets 2 is not guaranteed. It can change between runs. If you need a stable result, add a tie breaker to the window'sORDER BY, such asORDER BY salary DESC, emp_id.
Which one should you use?
ROW_NUMBER()when you need exactly one row per position, for example to remove duplicates by keeping row number 1.RANK()for competition-style ranking ("two people tied for 2nd, nobody is 3rd").DENSE_RANK()for questions like "find the second highest salary", where ties should not create gaps.
5. Ranking Across the Whole Table
Leave out PARTITION BY and the whole table becomes one window. Here the gap after a tie becomes visible, and two more functions join in:
SELECT name,
salary,
RANK() OVER (ORDER BY salary DESC) AS rank,
DENSE_RANK() OVER (ORDER BY salary DESC) AS dense_rank,
NTILE(3) OVER (ORDER BY salary DESC) AS salary_band,
PERCENT_RANK() OVER (ORDER BY salary DESC) AS pct_rank
FROM employees
ORDER BY salary DESC, name
+-----+------+----+----------+-----------+-------------------+
|name |salary|rank|dense_rank|salary_band|pct_rank |
+-----+------+----+----------+-----------+-------------------+
|Asha |95000 |1 |1 |1 |0.0 |
|Ben |82000 |2 |2 |1 |0.16666666666666666|
|Farid|82000 |2 |2 |1 |0.16666666666666666|
|Divya|65000 |4 |3 |2 |0.5 |
|Chen |60000 |5 |4 |2 |0.6666666666666666 |
|Elena|58000 |6 |5 |3 |0.8333333333333334 |
|Grace|45000 |7 |6 |3 |1.0 |
+-----+------+----+----------+-----------+-------------------+
RANK()jumps from 2 to 4 after the tie;DENSE_RANK()goes on with 3.NTILE(3)splits the ordered rows into 3 buckets that are as equal as possible. With 7 rows, the first bucket gets the extra row (3, 2, 2). It is handy for "top third / middle / bottom third" style banding.PERCENT_RANK()is(rank - 1) / (rows - 1): 0.0 for the first row, 1.0 for the last.
When there is no PARTITION BY, Spark has to move all rows to a single task to compute the window. That is fine for small data, but on a large table it creates a bottleneck. Partition by a key whenever the question allows it.
6. Aggregates Over a Window
Any aggregate (SUM, AVG, MIN, MAX, COUNT) can be used with OVER. This is the classic way to compare a row with its group:
SELECT name,
dept,
salary,
COUNT(*) OVER (PARTITION BY dept) AS dept_size,
MAX(salary) OVER (PARTITION BY dept) AS dept_max,
ROUND(salary - AVG(salary) OVER (PARTITION BY dept), 2) AS diff_from_avg,
ROUND(100 * salary / SUM(salary) OVER (PARTITION BY dept), 1) AS pct_of_dept
FROM employees
WHERE dept IS NOT NULL
ORDER BY dept, salary DESC, name
+-----+-----------+------+---------+--------+-------------+-----------+
|name |dept |salary|dept_size|dept_max|diff_from_avg|pct_of_dept|
+-----+-----------+------+---------+--------+-------------+-----------+
|Asha |Engineering|95000 |3 |95000 |8666.67 |36.7 |
|Ben |Engineering|82000 |3 |95000 |-4333.33 |31.7 |
|Farid|Engineering|82000 |3 |95000 |-4333.33 |31.7 |
|Elena|Marketing |58000 |1 |58000 |0.0 |100.0 |
|Divya|Sales |65000 |2 |65000 |2500.0 |52.0 |
|Chen |Sales |60000 |2 |65000 |-2500.0 |48.0 |
+-----+-----------+------+---------+--------+-------------+-----------+
Reading the Engineering rows: there are 3 people, the top salary is 95000, Asha earns 8666.67 more than the department average, and she takes 36.7% of the department's salary budget.
Without the window, you would need a GROUP BY subquery and a join back to employees to get the same result. The window version is shorter and easier to read.
Common mistake: Adding
ORDER BYinsideOVERchanges an aggregate's meaning.SUM(salary) OVER (PARTITION BY dept)is the department total on every row, butSUM(salary) OVER (PARTITION BY dept ORDER BY hire_date)is a running total by hire date. The reason is the default frame, explained in Window Frames.
7. Top N per Group
"Find the highest-paid employee in each department" is one of the most common interview questions. You cannot filter on a window function in WHERE, because WHERE runs before the window is computed:
SELECT name, dept, salary,
ROW_NUMBER() OVER (PARTITION BY dept ORDER BY salary DESC) AS rn
FROM employees
WHERE rn = 1
[UNRESOLVED_COLUMN.WITH_SUGGESTION] A column or function parameter with name `rn` cannot be resolved. Did you mean one of the following? [`name`, `city`, `dept`, `salary`, `emp_id`].; line 4 pos 6;
The fix is to compute the window in a CTE (or subquery) first, then filter the result:
WITH ranked AS (
SELECT name,
dept,
salary,
DENSE_RANK() OVER (PARTITION BY dept ORDER BY salary DESC) AS rnk
FROM employees
WHERE dept IS NOT NULL
)
SELECT dept, name, salary, rnk
FROM ranked
WHERE rnk <= 2
ORDER BY dept, rnk, name
+-----------+-----+------+---+
|dept |name |salary|rnk|
+-----------+-----+------+---+
|Engineering|Asha |95000 |1 |
|Engineering|Ben |82000 |2 |
|Engineering|Farid|82000 |2 |
|Marketing |Elena|58000 |1 |
|Sales |Divya|65000 |1 |
|Sales |Chen |60000 |2 |
+-----------+-----+------+---+
This returns the top 2 salaries per department. Engineering returns three people, because Ben and Farid share rank 2. That is why the choice of function matters:
DENSE_RANK() ... <= 2returns everyone with one of the top 2 salaries, including ties.ROW_NUMBER() ... <= 2returns exactly 2 rows per department, dropping one of the tied employees.
Some SQL engines (Databricks, Snowflake) offer a QUALIFY clause that filters on window functions directly. Spark 3.5 does not support it:
SELECT name, dept, salary,
ROW_NUMBER() OVER (PARTITION BY dept ORDER BY salary DESC) AS rn
FROM employees
QUALIFY rn = 1
[PARSE_SYNTAX_ERROR] Syntax error at or near 'rn'.(line 4, pos 8)
Spark does not know the QUALIFY keyword, so it reads QUALIFY as a table alias for employees and then fails at rn. In Spark 3.5, stick to the CTE pattern above. It works everywhere.
8. Reusing a Window with the WINDOW Clause
When several functions share the same window, you can name it once with a WINDOW clause and refer to it by name:
SELECT name,
dept,
salary,
RANK() OVER w AS rank,
DENSE_RANK() OVER w AS dense_rank
FROM employees
WHERE dept IS NOT NULL
WINDOW w AS (PARTITION BY dept ORDER BY salary DESC)
ORDER BY dept, rank, name
+-----+-----------+------+----+----------+
|name |dept |salary|rank|dense_rank|
+-----+-----------+------+----+----------+
|Asha |Engineering|95000 |1 |1 |
|Ben |Engineering|82000 |2 |2 |
|Farid|Engineering|82000 |2 |2 |
|Elena|Marketing |58000 |1 |1 |
|Divya|Sales |65000 |1 |1 |
|Chen |Sales |60000 |2 |2 |
+-----+-----------+------+----+----------+
The WINDOW clause goes after WHERE (and after GROUP BY and HAVING if present), before ORDER BY. It saves typing and keeps the windows consistent, since you cannot accidentally change one copy.
9. Ranking Needs an ORDER BY
Ranking functions only make sense in some order, so Spark rejects them without one:
SELECT name, ROW_NUMBER() OVER (PARTITION BY dept) AS rn
FROM employees
Window function row_number() requires window to be ordered, please add ORDER BY clause. For example SELECT row_number()(value_expr) OVER (PARTITION BY window_partition ORDER BY window_ordering) from table.
Aggregates like SUM and AVG are fine without ORDER BY; ranking functions (ROW_NUMBER, RANK, DENSE_RANK, NTILE, PERCENT_RANK) are not.
10. Try It in the Online Compiler
Copy this into the PySpark Online Compiler. Each spark.sql() call holds one statement:
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName("Spark SQL Window Functions").getOrCreate()
spark.sql("""
CREATE OR REPLACE TEMP VIEW employees AS
SELECT * FROM VALUES
(1, 'Asha', 'Engineering', 95000, DATE'2019-03-15', NULL, 'Bengaluru'),
(2, 'Ben', 'Engineering', 82000, DATE'2020-07-01', 1, 'Pune'),
(3, 'Chen', 'Sales', 60000, DATE'2021-01-10', 1, 'Mumbai'),
(4, 'Divya', 'Sales', 65000, DATE'2018-11-23', 3, 'Mumbai'),
(5, 'Elena', 'Marketing', 58000, DATE'2022-05-30', 1, NULL),
(6, 'Farid', 'Engineering', 82000, DATE'2023-02-14', 2, 'Bengaluru'),
(7, 'Grace', NULL, 45000, DATE'2024-01-08', NULL, 'Delhi')
AS employees(emp_id, name, dept, salary, hire_date, manager_id, city)
""")
# Rank within each department
spark.sql("""
SELECT name, dept, salary,
ROW_NUMBER() OVER (PARTITION BY dept ORDER BY salary DESC, emp_id) AS row_number,
RANK() OVER (PARTITION BY dept ORDER BY salary DESC) AS rank,
DENSE_RANK() OVER (PARTITION BY dept ORDER BY salary DESC) AS dense_rank
FROM employees
ORDER BY dept, salary DESC, name
""").show(truncate=False)
# Highest-paid employee per department
spark.sql("""
WITH ranked AS (
SELECT name, dept, salary,
ROW_NUMBER() OVER (PARTITION BY dept ORDER BY salary DESC, emp_id) AS rn
FROM employees
)
SELECT dept, name, salary FROM ranked WHERE rn = 1 ORDER BY dept
""").show(truncate=False)
Summary
- A window function adds a value to every row using a group of related rows, while
GROUP BYcollapses each group into one row. OVER (PARTITION BY ... ORDER BY ...)defines the window.PARTITION BYsplits rows into groups;ORDER BYsorts within each group.ROW_NUMBER()is always unique,RANK()leaves gaps after ties,DENSE_RANK()does not. Add a tie breaker whenROW_NUMBER()must be stable.- Aggregates over a window (
AVG(salary) OVER (PARTITION BY dept)) compare each row with its group without a join. - To filter on a window result (top N per group), compute it in a CTE and filter outside. Spark 3.5 has no
QUALIFY. - The
WINDOW w AS (...)clause names a window so several functions can share it.
Next, you will learn LEAD and LAG, which let each row look at the row before or after it.