← All Exercises

SQL Window Functions

intermediatesql~25min

Background

Window functions perform calculations across related rows without grouping, preserving individual row detail.

Problem

Write a SQL query to rank employees by salary within each department using the RANK window function.

Input

An employees table with id, name, department, salary columns.

Output

All employees with their salary rank within their department.

Sample tests

Sample 1

Input: employees in Sales with salaries 50k, 60k, 60k, 70k
Expected: ranks 4, 2, 2, 1 (ties get same rank)

Your solution

Learning objective

Learn window functions, PARTITION BY, ORDER BY in OVER, and RANK vs DENSE_RANK vs ROW_NUMBER.