RANK (Lakehouse v1)
The RANK() function assigns a unique rank to each value within an ordered group of values.
The rank value starts at 1 and continues up sequentially. If two values are the same, they have the same rank.
Analyze Syntax
Section titled “Analyze Syntax”func.rank().over(partition_by=[<columns>], order_by=[<columns>])Analyze Examples
Section titled “Analyze Examples”table.employee_id, table.first_name, table.last_name, table.department, table.salary, func.rank().over(order_by=table.salary).alias('rank')
| employee_id | first_name | last_name | department | salary | rank ||-------------|------------|-----------|------------|--------|------|| 1 | John | Doe | IT | 90000 | 1 || 2 | Jane | Smith | HR | 85000 | 2 || 3 | Mike | Johnson | IT | 82000 | 3 || 4 | Sara | Williams | Sales | 77000 | 4 || 5 | Tom | Brown | HR | 75000 | 5 |SQL Syntax
Section titled “SQL Syntax”RANK() OVER ( [ PARTITION BY <expr1> ] ORDER BY <expr2> [ { ASC | DESC } ] [ <window_frame> ])SQL Examples
Section titled “SQL Examples”Create the table
CREATE TABLE employees ( employee_id INT, first_name VARCHAR, last_name VARCHAR, department VARCHAR, salary INT);Insert data
INSERT INTO employees (employee_id, first_name, last_name, department, salary) VALUES (1, 'John', 'Doe', 'IT', 90000), (2, 'Jane', 'Smith', 'HR', 85000), (3, 'Mike', 'Johnson', 'IT', 82000), (4, 'Sara', 'Williams', 'Sales', 77000), (5, 'Tom', 'Brown', 'HR', 75000);Ranking employees by salary
SELECT employee_id, first_name, last_name, department, salary, RANK() OVER (ORDER BY salary DESC) AS rankFROM employees;Result:
| employee_id | first_name | last_name | department | salary | rank |
|---|---|---|---|---|---|
| 1 | John | Doe | IT | 90000 | 1 |
| 2 | Jane | Smith | HR | 85000 | 2 |
| 3 | Mike | Johnson | IT | 82000 | 3 |
| 4 | Sara | Williams | Sales | 77000 | 4 |
| 5 | Tom | Brown | HR | 75000 | 5 |