1.OVER(), PARTITION BY and ORDER BY in Window Expressions
OVER() turns an aggregate-like function into a window function: it computes across a set of related rows but keeps every row in the output, instead of collapsing them the way GROUP BY does. PARTITION BY defines which rows are "related"; ORDER BY inside OVER() defines the order the window function sees them in.
Key features
- OVER() marks a function as a window function — without it, the same function name may mean something else (or not exist) as an aggregate
- PARTITION BY splits rows into groups the window function is computed within, without collapsing them
- ORDER BY inside OVER() controls the order rows are processed in — required for ranking and offset functions like LAG/LEAD
- Omitting PARTITION BY treats the entire result set as one partition
- Window functions run after WHERE/GROUP BY/HAVING but before the final ORDER BY and LIMIT
GROUP BY vs a window function, side by side
- GROUP BY dept
- one output row per department
- individual employee rows are gone
- SELECT dept, avg(salary) FROM employees GROUP BY dept
- avg(salary) OVER (PARTITION BY dept)
- one output row per employee, unchanged
- each row also shows its department's average
- nothing is collapsed
Command
SELECT name, dept, salary,
avg(salary) OVER (PARTITION BY dept ORDER BY salary) AS running_dept_avg
FROM employees;OVER() computes across a set of related rows without collapsing them — PARTITION BY groups rows the same way GROUP BY would, but every original row survives in the output.