OVER clause with PARTITION BY in SQL - Time & Space Complexity
We want to understand how the time to run a query with the OVER clause and PARTITION BY grows as the data gets bigger.
Specifically, how does dividing data into groups affect the work done?
Analyze the time complexity of the following code snippet.
SELECT employee_id, department_id, salary,
RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS dept_rank
FROM employees;
This query ranks employees by salary within each department.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Sorting employees within each department to assign ranks.
- How many times: Once per department group, sorting all employees in that group.
As the number of employees grows, the query sorts each department's employees separately.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 log 10 operations (sorting small groups) |
| 100 | About 100 log 100 operations (sorting larger groups) |
| 1000 | About 1000 log 1000 operations (sorting even larger groups) |
Pattern observation: The work grows a bit faster than the number of rows because sorting takes more time as groups get bigger.
Time Complexity: O(n log n)
This means the time to run the query grows a bit faster than the number of rows because sorting is needed within each group.
[X] Wrong: "The PARTITION BY makes the query run in linear time because it splits the data."
[OK] Correct: Even though data is split, each group still needs sorting, which takes more than just looking at each row once.
Understanding how window functions like OVER with PARTITION BY affect performance shows you know how databases handle grouped data efficiently.
"What if we removed the PARTITION BY clause and ranked all employees together? How would the time complexity change?"
Practice
PARTITION BY clause do when used with the OVER clause in SQL?Solution
Step 1: Understand the role of PARTITION BY
ThePARTITION BYclause groups rows based on column values, similar to grouping in real life like sorting students by class.Step 2: See how OVER uses PARTITION BY
TheOVERclause applies functions like SUM or ROW_NUMBER within each group separately, not on the whole table.Final Answer:
It divides the result set into groups to perform calculations within each group. -> Option AQuick Check:
PARTITION BY = group rows for calculations [OK]
- Confusing PARTITION BY with WHERE filtering
- Thinking PARTITION BY sorts all rows globally
- Assuming PARTITION BY removes duplicates
OVER with PARTITION BY?Solution
Step 1: Identify correct OVER clause order
The correct syntax placesPARTITION BYbeforeORDER BYinside the parentheses afterOVER.Step 2: Check each option's syntax
SELECT department, sales, SUM(sales) OVER (PARTITION BY department ORDER BY date) AS running_total FROM sales_data; correctly usesSUM(sales) OVER (PARTITION BY department ORDER BY date). Others misplace PARTITION BY or OVER keywords.Final Answer:
SELECT department, sales, SUM(sales) OVER (PARTITION BY department ORDER BY date) AS running_total FROM sales_data; -> Option BQuick Check:
PARTITION BY before ORDER BY inside OVER [OK]
- Swapping PARTITION BY and ORDER BY order
- Placing PARTITION BY outside OVER parentheses
- Using PARTITION BY without OVER
Employees with columns Department and Salary, what will the following query return?SELECT Department, Salary, RANK() OVER (PARTITION BY Department ORDER BY Salary DESC) AS SalaryRank FROM Employees;
Solution
Step 1: Understand RANK() with PARTITION BY
TheRANK()function assigns ranks starting at 1 within each partition (department), ordered by salary descending.Step 2: Analyze the query output
Each employee gets a rank based on salary within their department, highest salary ranked 1, ties get same rank.Final Answer:
Ranks salaries within each department from highest to lowest, starting at 1 for the highest salary. -> Option DQuick Check:
RANK() OVER PARTITION BY groups and ranks rows [OK]
- Thinking RANK() ignores PARTITION BY
- Confusing RANK() with SUM()
- Assuming ranking is global, not per group
SELECT employee_id, department, SUM(salary) OVER PARTITION BY department FROM employees;
Solution
Step 1: Check OVER clause syntax
TheOVERclause must have parentheses enclosingPARTITION BYand other clauses.Step 2: Identify missing parentheses
The query misses parentheses after OVER, it should beOVER (PARTITION BY department).Final Answer:
Missing parentheses around PARTITION BY clause inside OVER. -> Option CQuick Check:
OVER requires parentheses around PARTITION BY [OK]
- Omitting parentheses after OVER
- Using aggregate without OVER for window function
- Including wrong columns in PARTITION BY
OVER with PARTITION BY to achieve this?Solution
Step 1: Use correct syntax for RANK() and AVG() with PARTITION BY
Both functions must haveOVER (PARTITION BY class ...). RANK() orders descending for highest score first; AVG() just partitions by class.Step 2: Check each option's correctness
SELECT student_id, class, score, RANK() OVER (PARTITION BY class ORDER BY score DESC) AS rank_in_class, AVG(score) OVER (PARTITION BY class) AS avg_class_score FROM student_scores; correctly usesRANK() OVER (PARTITION BY class ORDER BY score DESC)andAVG(score) OVER (PARTITION BY class). Others have syntax errors or wrong order.Final Answer:
SELECT student_id, class, score, RANK() OVER (PARTITION BY class ORDER BY score DESC) AS rank_in_class, AVG(score) OVER (PARTITION BY class) AS avg_class_score FROM student_scores; -> Option AQuick Check:
Use OVER (PARTITION BY ...) with correct order and parentheses [OK]
- Mixing ORDER BY and PARTITION BY order inside OVER
- Missing parentheses around PARTITION BY
- Using PARTITION BY without OVER
Ready to prove it?
Pass the test and this pattern moves unknown
