Lecture

PARTITION BY

The PARTITION BY clause is used with window functions to divide rows into groups, allowing each group to be processed independently.

It works similarly to GROUP BY, but unlike GROUP BY, it does not collapse rows. Instead, it retains all rows while logically segmenting them for window function calculations.


Syntax

You can use PARTITION BY to group rows into partitions.

PARTITION BY syntax
SELECT column, window_function(...) OVER ( PARTITION BY group_column ORDER BY sort_column ) AS result FROM table;
  • PARTITION BY splits rows into groups.
  • ORDER BY sorts rows within each group.

Example: Rank Students Within Each Class

Assume we have the following table:

scores

nameclassscore
AlexA92
SaraA95
DanielA88
MiaB90
JohnB85
EmmaB93

We want to rank students within each class by their score.

Using PARTITION BY
SELECT name, class, score, RANK() OVER ( PARTITION BY class ORDER BY score DESC ) AS rank_in_class FROM scores;

The query returns the following:

Result:

nameclassscorerank_in_class
SaraA951
AlexA922
DanielA883
EmmaB931
MiaB902
JohnB853

Here, each class has its own ranking system because of PARTITION BY class.


In general, PARTITION BY splits rows into groups so window functions calculate results within each group rather than across the entire table.

Quiz
0 / 1

What is the main difference between the RANK() and DENSE_RANK() functions in SQL?

RANK() assigns the same rank to all rows with the same value and skips the next rank.

DENSE_RANK() assigns different ranks to all rows regardless of value.

RANK() assigns a unique rank to each row even if values are the same.

DENSE_RANK() skips ranks after encountering identical values.

Lecture

AI Tutor

Design

Upload

Notes

Favorites

Help

Code Editor

Run
Generate

Tables

Execution Result