r/SQL • u/Harshita_Netla • Sep 21 '26
MySQL Practicing window functions and keep mixing up PARTITION BY vs GROUP BY — how are they actually different?
They both seem like they divide data into groups, so I’m having trouble understanding when I should use one instead of the other.
47
Upvotes
View all comments
2
u/Legitimate-Pin-8619 Sep 22 '26
They both “group” rows, but they do different jobs.
`GROUP BY` collapses rows. After it runs you only get one output row per group (plus aggregates). You lose the individual row values unless you aggregate them.
`PARTITION BY` (in a window function) does **not** collapse rows. It tells the window which peer group to compute over, but every input row still comes back. That’s why you can do things like “show each order and that customer’s total” in one pass:
```sql
SELECT
customer_id,
order_id,
amount,
SUM(amount) OVER (PARTITION BY customer_id) AS customer_total,
ROW_NUMBER() OVER (
PARTITION BY customer_id
ORDER BY amount DESC
) AS rank_in_customer
FROM orders;