Sub topic 4
Ordering Rows Inside a Window
Assume you know SELECT, WHERE, GROUP BY, aggregate functions, subqueries, and common table expressions (CTEs). This chapter focuses on the ORDER BY inside an OVER clause.
What window ordering does
A window function evaluates rows in a defined window. The window's ORDER BY tells the database how to arrange those rows for calculations such as ranking, running totals, and comparisons with previous rows.
This ordering is separate from the query's final ORDER BY.
SELECT
salesperson,
amount,
ROW_NUMBER() OVER (ORDER BY amount DESC) AS sales_position
FROM sales
ORDER BY salesperson;The window orders rows by amount DESC to assign positions. The final ORDER BY salesperson controls how the result is displayed. The displayed rows do not need to appear in sales-position order.
A window ORDER BY usually has this form:
function_name() OVER (
PARTITION BY grouping_columns
ORDER BY ordering_columns
)PARTITION BY is optional. Without it, all result rows belong to one window. With it, the database creates a separate ordered window for each partition.
Choosing ascending or descending order
Use ASC for smallest-to-largest or oldest-to-newest order. Use DESC for largest-to-smallest or newest-to-oldest order.
SELECT
region,
salesperson,
amount,
ROW_NUMBER() OVER (
PARTITION BY region
ORDER BY amount DESC
) AS regional_position
FROM sales;This gives each salesperson a position within their region. The largest sale receives position 1.
You can order by multiple columns. The database uses the next column when earlier values tie.
SELECT
id,
region,
salesperson,
amount,
ROW_NUMBER() OVER (
PARTITION BY region
ORDER BY amount DESC, id ASC
) AS regional_position
FROM sales;Here, amount DESC is the main ordering. If two sales have the same amount, the smaller id comes first.
Ties and ranking functions
Different ranking functions handle ties differently.
| Function | Tied rows | Gaps after ties |
|---|---|---|
| `ROW_NUMBER()` | Always assigns different numbers | Not applicable |
| `RANK()` | Assigns the same number | Yes |
| `DENSE_RANK()` | Assigns the same number | No |
SELECT
salesperson,
amount,
ROW_NUMBER() OVER (ORDER BY amount DESC) AS row_num,
RANK() OVER (ORDER BY amount DESC) AS rnk,
DENSE_RANK() OVER (ORDER BY amount DESC) AS dense_rnk
FROM sales;If the amounts are 100, 100, and 80, the results are:
| Amount | `ROW_NUMBER()` | `RANK()` | `DENSE_RANK()` |
|---|---|---|---|
| 100 | 1 or 2 | 1 | 1 |
| 100 | 2 or 1 | 1 | 1 |
| 80 | 3 | 3 | 2 |
Use ROW_NUMBER() when every row needs a unique position. Use RANK() when tied rows should share a competition ranking. Use DENSE_RANK() when tied ranks should not create gaps.
Exercise
Exercise
Which function should you use to select exactly one row as position 1, even when several rows have the same amount?
Show answer
Use ROW_NUMBER(), adding a deterministic tie-breaker such as id to the window ORDER BY.