PARTITION BY Clause & Window Definition: Concept
Module: Window Functions
Think of PARTITION BY as creating separate "lanes" on a highway. Without PARTITION BY, all cars (rows) are in one massive lane, and any calculation affects everyone equally. With PARTITION BY, you create dedicated lanes - one for trucks, one for cars, one for motorcycles. Now each lane can have its own speed limit (calculation) while still being part of the same highway (query result). This is exactly what PARTITION BY does: it divides your data into logical groups, applies window functions separately to each group, but keeps all rows in the final result. It's like having multiple GROUP BY operations running simultaneously, but without losing any individual row details.
**
**Understanding PARTITION BY Fundamentals:**
PARTITION BY is the grouping mechanism for window functions. Unlike GROUP BY which collapses rows into groups, PARTITION BY creates invisible boundaries between groups while preserving every row.
```sql
-- GROUP BY: Collapses to group summaries (loses detail)
SELECT department, AVG(salary) as avg_salary
FROM employees
GROUP BY department;
-- Result: 3 rows (one per department)
-- PARTITION BY: Keeps all rows with group calculations
SELECT
employee_name,
department,
salary,
AVG(salary) OVER (PARTITION BY department) as dept_avg_salary
FROM employees;
-- Result: All original rows + department averages
```
**Single Column Partitioning:**
The most common pattern - partition by one column to create logical groups:
```sql
-- Rank employees within each department
SELECT
employee_name,
department,
salary,
RANK() OVER (PARTITION BY department ORDER BY salary DESC) as dept_rank,
COUNT(*) OVER (PARTITION BY department) as dept_size
FROM employees;
-- Results show:
-- Sales: Alice (rank 2), Bob (rank 1) - 2 people
-- IT: Carol (rank 2), Dave (rank 1) - 2 people
-- HR: Eve (rank 1) - 1 person
```
**Multiple Column Partitioning:**
Create more granular groups by partitioning on multiple columns:
```sql
-- Partition by department AND experience level
SELECT