Challenge - 5 Problems
Window Function Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2:00remaining
Output of ROW_NUMBER() window function
Given a table employees with columns
id, department, and salary, what is the output of this query?SELECT id, department, salary, ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rank FROM employees;
PostgreSQL
CREATE TABLE employees (id INT, department TEXT, salary INT); INSERT INTO employees VALUES (1, 'Sales', 5000), (2, 'Sales', 7000), (3, 'HR', 4000), (4, 'HR', 4500), (5, 'IT', 6000);
Attempts:
2 left
💡 Hint
Remember that ROW_NUMBER() resets for each department and orders salaries descending.
✗ Incorrect
ROW_NUMBER() assigns a unique rank starting at 1 within each department partition, ordered by salary descending. So highest salary in each department gets rank 1.
🧠 Conceptual
intermediate1:30remaining
Why use window functions instead of GROUP BY?
Which statement best explains why window functions are powerful compared to GROUP BY?
Attempts:
2 left
💡 Hint
Think about whether the number of rows changes after using window functions.
✗ Incorrect
Window functions compute values across rows but keep all original rows intact, unlike GROUP BY which aggregates and reduces rows.
📝 Syntax
advanced1:30remaining
Identify the syntax error in this window function query
What is wrong with this SQL query?
SELECT id, salary, RANK() OVER (ORDER salary DESC) AS rank FROM employees;
Attempts:
2 left
💡 Hint
Check the syntax of the ORDER BY clause inside the OVER() window function.
✗ Incorrect
The correct syntax requires ORDER BY, not just ORDER, inside the OVER() clause.
❓ optimization
advanced2:00remaining
Optimizing a query with window functions
You have a large sales table and want to calculate the running total of sales per region ordered by date. Which approach is most efficient?
Attempts:
2 left
💡 Hint
Window functions can compute running totals efficiently inside the database.
✗ Incorrect
Using SUM() as a window function with proper partitioning and ordering is optimized by the database engine and avoids expensive subqueries or joins.
🔧 Debug
expert2:30remaining
Debugging unexpected results with window functions
A query uses ROW_NUMBER() OVER (ORDER BY salary) but returns unexpected row numbering when multiple employees have the same salary. What is the cause?
Attempts:
2 left
💡 Hint
Think about how ROW_NUMBER() handles ties in ordering.
✗ Incorrect
ROW_NUMBER() always assigns unique sequential numbers. When ORDER BY values tie, the order among those tied rows is arbitrary and can cause unexpected numbering.