Group by function on a table
What is a Window Function?
A window function in PostgreSQL performs calculations across a set of table rows related to the
current row. Unlike aggregate functions (which collapse rows into a single result), window functions
preserve individual rows while computing values across a group.
Key Components of Window Functions
1. Function – The calculation to be performed (e.g., ROW_NUMBER(), RANK(), SUM(), AVG(),
etc.).
2. OVER() Clause – Defines how the function's window is partitioned.
3. PARTITION BY – Divides the dataset into partitions (optional).
4. ORDER BY – Defines the order of rows within each partition.
ROW_NUMBER():
1)Assigns a unique row number to each row (even if values are duplicated).
2)No gaps in numbering.
3)Does not consider ties—each row gets a unique number.
Example Query:
RANK():
Assigns the same rank to rows with the same value.
Skips numbers after duplicates (i.e., introduces gaps).
If two rows have the same value, they get the same rank, and the next rank is skipped.
DENSE_RANK():
Similar to RANK(), but does NOT skip numbers after ties.
Ensures consecutive ranking numbers (no gaps).
If your confused take a look at Simple Example of finding popularity of names: