The ROW_NUMBER()
function assigns a unique sequential integer to each row within the result set, starting from 1. Unlike RANK()
or DENSE_RANK()
, which may assign the same rank to tied values, ROW_NUMBER()
always generates a unique value. This makes it particularly useful for scenarios requiring unique identifiers for each row. For example:
sqlCopy codeSELECT employee_id, salary, ROW_NUMBER() OVER (ORDER BY salary DESC) AS row_num FROM employees;
This query assigns a unique row number to each employee based on their salary, allowing for easy identification and manipulation of rows. The use of ROW_NUMBER()
is especially helpful in pagination scenarios, where you might need to display a specific range of results, such as the top 10 employees by salary.
Leave a Reply