SQL Practice Logo

SQLPractice Online

Ranking Functions Deep Dive: Functions

Module: Window Functions

**Basic Ranking Function Syntax:**

```sql

SELECT

column1,

column2,

RANKING_FUNCTION() OVER (

[PARTITION BY column(s)]

ORDER BY column(s) [ASC|DESC]

) AS rank_alias

FROM table_name;

```

**Complete Comparison Example:**

```sql

-- Sample data: Employee salaries with ties

WITH sample_data AS (

SELECT 'Alice' as name, 100000 as salary UNION ALL

SELECT 'Bob', 90000 UNION ALL

SELECT 'Carol', 90000 UNION ALL -- Tie with Bob

SELECT 'Dave', 80000 UNION ALL

SELECT 'Eve', 80000 UNION ALL -- Tie with Dave

SELECT 'Frank', 70000

)

SELECT

name,

salary,

-- ROW_NUMBER: Always unique (1,2,3,4,5,6)

ROW_NUMBER() OVER(ORDER BY salary DESC) as row_num,

-- RANK: Gaps after ties (1,2,2,4,4,6)

RANK() OVER(ORDER BY salary DESC) as rank_with_gaps,

-- DENSE_RANK: No gaps (1,2,2,3,3,4)

DENSE_RANK() OVER(ORDER BY salary DESC) as dense_rank

FROM sample_data

ORDER BY salary DESC, name;

```

**Partitioned Rankings:**

```sql

-- Rankings within each department

SELECT

employee_name,

department,