Understand the concept
Windows calculate across related rows while keeping each input row. PARTITION BY resets the calculation; ORDER BY sets its sequence. The final result still needs its own ORDER BY.
Apply the method
ROW_NUMBER assigns a unique sequence; RANK leaves gaps after ties; DENSE_RANK does not. Two employees differs from two salary bands. Use a tie-breaker for selecting rows, but do not accidentally break salary ties when ranking bands.
Avoid a common mistake
For running totals, write an explicit ROWS frame. Default peer handling may include all rows with the same ordering value. LAG and LEAD return NULL at an edge unless a default is supplied. Filter window results in an outer query.
Worked query
Return name and salary_rank using DENSE_RANK descending by known salary. Exclude NULL; order by salary_rank,name.
SELECT name,DENSE_RANK() OVER(ORDER BY salary DESC) AS salary_rank FROM employees WHERE salary IS NOT NULL ORDER BY salary_rank,name;Run and explore this example →Check your understanding
Before running your query, predict the output columns and approximate row count. After running it, inspect a missing value, a tie and a record with no match when available. Explain why the result answers the question.
Practice this topic
- Salary ranking — Return name and salary_rank using DENSE_RANK descending by known salary. Exclude NULL; order by salary_rank,name.
- Department ranking — Return department,name,pay_rank using DENSE_RANK per department by descending known salary. Order by department,pay_rank,name.
- Order sequence — Return id and order_number using ROW_NUMBER per customer by ordered_at,id. Order output by id.
- Running paid revenue — Return id and running_total across paid orders by ordered_at,id. Use ROWS UNBOUNDED PRECEDING. Order by ordered_at,id.
- Previous order amount — Return id and previous_amount using LAG within customer by ordered_at,id, any status. Order output by id.
- Next order date — Return id and next_order using LEAD of ordered_at per customer by ordered_at,id. Order output by id.
- Attach departmental payroll — Return name and department_total using a window SUM, including employees with NULL salary. Order by id.
- Latest order per customer — Return customer_id and order_id for the latest order per customer. Latest date wins, then highest id. Order by customer_id.
- Top two salary bands — Return department and name for top two distinct known salary bands per department, retaining ties. Order by department,name.
- Three-order moving mean — Return id and moving_average rounded to two decimals for each paid order and up to two preceding paid orders, by ordered_at,id.
SQLite reference: SQL language documentation. Written by Future Data Academy with AI assistance; query examples checked against the supplied teaching dataset.
