PARTITION BY: Splits rows into groups for a window function — like GROUP BY, but the rows are kept. PARTITION BY splits rows into groups for a window function, without merging them. AVG(salary) OVER (PARTITION BY department) gives every employee the average salary of their own department. It is like GROUP BY for window functions, except every row stays in the result. That makes questions like "each order and its share of the customer's total" or "the three most recent orders per customer" possible in one query.
A common pattern combines it with ROW_NUMBER(): number rows per customer by date, then keep the rows numbered 1 to 3. That replaces loops in application code that load everything and filter afterwards. An index on the partition and ordering columns, such as (customer_id, created_at), helps the database do this efficiently on large tables.
What does an example of PARTITION BY look like?
SELECT dept, name, salary, AVG(salary) OVER (PARTITION BY dept) AS dept_avg FROM employees;