![]() |
VOOZH | about |
The PARTITION BY clause in MySQL divides the result set into smaller groups so calculations can be performed independently within each group. It is mainly used with window functions to analyze related rows without affecting the entire dataset.
Syntax:
window_function(expression)
OVER (
PARTITION BY column_name
[ORDER BY column_name]
[frame_clause]
);First, we will create a demo table on which the PARTITION BY Clause will be applied:
We have to find the rank of hackers in each challenge. That means we have to list all participated hackers of a challenge along with their rank in that challenge.
Query:
SELECT
challenge_id,
h_id,
h_name,
score,
DENSE_RANK() OVER (
PARTITION BY challenge_id
ORDER BY score DESC
) AS `rank`
FROM hacker;Output:
We want to find the next hackerβs score within each challenge.
Query:
SELECT
challenge_id,
h_name,
score,
LEAD(score) OVER (
PARTITION BY challenge_id
ORDER BY score DESC
) AS next_score
FROM hacker;Output:
Here are some key differences between PARTITION BY and GROUP BY:
PARTITION BY | GROUP BY |
|---|---|
Used with window functions | Used with aggregate functions |
Does not reduce number of rows | Reduces rows into summary |
Returns original rows with extra calculations | Returns one row per group |
Performs calculations within partitions | Performs calculations on grouped data |
Used with OVER() clause | Used directly in SELECT query |