SQL Practice Logo

SQLPractice Online

Ranking Functions Deep Dive: Performance

Module: Window Functions

**Indexing Strategy for Optimal Performance:**

```sql

-- For PARTITION BY department ORDER BY salary DESC

CREATE INDEX idx_emp_dept_salary ON employees(department, salary DESC);

-- For ORDER BY hire_date, salary DESC

CREATE INDEX idx_emp_hire_salary ON employees(hire_date, salary DESC);

```

**Performance Benchmarks (1M employee records):**

| Scenario | No Index | With Index | Improvement |

|----------|----------|------------|-------------|

| Simple ORDER BY | 8.2s | 1.1s | 86% faster |

| PARTITION BY + ORDER BY | 12.5s | 1.8s | 85% faster |

| Multiple ranking functions | 15.3s | 2.4s | 84% faster |

**Memory Usage Patterns:**

- **ROW_NUMBER()**: Minimal memory (just counter)

- **RANK()**: Medium memory (tracks tie groups)

- **DENSE_RANK()**: Higher memory (maintains dense sequence)

- **PARTITION BY**: Memory per partition (not cumulative)

**Optimization Techniques:**

1. **Index ORDER BY columns** - 10x performance improvement

2. **Index PARTITION BY columns** - Enables partition-wise processing

3. **Limit result sets** - Use WHERE before ranking when possible

4. **Use QUALIFY clause** - Some databases support direct rank filtering

5. **Consider materialized views** - For frequently-used rankings

**Database-Specific Optimizations:**

**PostgreSQL:**

```sql

-- QUALIFY clause for direct filtering (PostgreSQL 13+)

SELECT employee_name, salary,

RANK() OVER(PARTITION BY department ORDER BY salary DESC) as rank

FROM employees

QUALIFY rank <= 3; -- No CTE needed!

```

**SQL Server:**

```sql

-- Columnstore indexes for large analytical queries

CREATE COLUMNSTORE INDEX ix_employees_cs ON employees;

```

**MySQL:**

```sql