Skip to main content
SQL • LESSON 27

SQL PARTITION BY

How can we compute rankings or window metrics independently within each department?

Advanced3 Minutes460 XP
🤔 THE QUESTION

How can we compute rankings or window metrics independently within each department?

💡 WHAT IS IT?

PARTITION BY divides the result set into window partitions before applying analytical functions.

🎯 WHAT IS IT USED FOR?

Ranking employees within their department, calculating customer-level metrics in event logs.

💻 EXAMPLE
SELECT name,
department,
salary,
RANK() OVER (
  PARTITION BY department
  ORDER BY salary DESC
) AS department_rank
FROM employees;

🎯 Mission Objectives

Practice typing production-grade SQL code for SQL PARTITION BY.

  • PARTITION BY
  • Scoped window
  • Group ranking
  • OVER (PARTITION BY)