Skip to content

ROW_NUMBER

ROW_NUMBER() OVER ([PARTITION BY column_1, column_2, …] [ORDER BY column_3, column_4, …])

Section titled “ROW_NUMBER() OVER ([PARTITION BY column_1, column_2, …] [ORDER BY column_3, column_4, …])”
SELECT name,
age,
ROW_NUMBER() OVER(ORDER BY age DESC) AS RowNum
FROM students
| name | age | RowNum |
|-------|-----|--------|
| John | 22 | 1 |
| Alice | 20 | 2 |
| Bob | 19 | 3 |

In the SQL provided, ROW_NUMBER() is a window function that assigns a unique, sequential integer to each row within the partition of the result set that was defined by the OVER() clause. The OVER() clause has an ORDER BY statement which orders the rows by age in descending order before the ROW_NUMBER() function is applied. This results in the oldest student getting the row number 1, and so forth.