DELAPARRA
Index
Color
NL
Category: SQL

PARTITION BY

Explained by Updated

What is PARTITION BY?

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.

Definition source Coders Lingo, CC BY 4.0

Frequently asked questions about PARTITION BY

What should you keep in mind with PARTITION BY?

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;

At a glance

CategorySQL
Explained by
Updated

More SQL terms

All terms starting with P

Skills

Download all skills (zip)

Manuals

Related services

Need any help?

Stuck on one of these in your own project? Tell me what you are working on and I will tell you how I would approach it.