Skip to content

OVER

<window function> OVER ([PARTITION BY <expression>[,…]] [ORDER BY <expression> [ASC|DESC][,…] [ROWS|RANGE <frame specification>]])

Section titled “<window function> OVER ([PARTITION BY <expression>[,…]] [ORDER BY <expression> [ASC|DESC][,…] [ROWS|RANGE <frame specification>]])”
  • <window function>: A built-in function in SQL used for performing calculations across a set of table rows related to the current row. These include cumulative, moving, and aggregate functions such as SUM, AVG, MAX, MIN, COUNT, and row_number.
  • over (): Defines window partitions to perform the calculation over. It is a required clause when calling a window function.
  • partition by <expression>[,…]: Defines a column or columns to group data into separate partitions on which the window function will be applied. Each partition forms a subset of the data, operating independently from other partitions.
  • order by <expression> [asc|desc][,…]: Specifies an ordering of rows within a partition. The window function is computed across the ordered rows within each partition. ASC (ascending) or DESC (descending) can be used to define the order; if not specified, ASC is default. Multiple Expressions can be used, separated by commas.
  • rows|range <frame specification>: Specifies the rows or range of values to include in the frame. The frame is a set of rows related to the current row from which the values are derived for processing. Range uses logical offsets (based on values), while Rows uses physical offsets (based on row position).
SELECT customer_name,
total_purchase,
RANK() OVER (ORDER BY total_purchase DESC) as purchase_rank
FROM customers;
| customer_name | total_purchase | purchase_rank |
| :------------ | :------------- | :------------ |
| John Doe | 500 | 1 |
| Jane Doe | 300 | 2 |
| Mary Smith | 200 | 3 |

The OVER() clause is used here along with RANK() function to rank customers based on their total purchases. Customers with highest total purchases get the top ranks. In our result set, ‘John Doe’, who made the highest total purchase is ranked as 1 and so on.