SQL-Engineering-Handbook

RANK()

RANK competition ranking diagram showing gaps after ties

Overview

RANK() assigns a competition-style rank to each row. Rows with equal ORDER BY values receive the same rank, and the next rank skips the number of tied rows (like Olympic medal standings).

Ordered values: [10, 20, 20, 40]
RANK():         [1,  2,  2,  4]

Learning Objectives

Prerequisites

Syntax

SELECT
    column_a,
    RANK() OVER (ORDER BY sort_column) AS rank_value
FROM table_name;

Dataset Used

employes, departments, locations

Examples

See 02_rank.sql.

Real World Applications

Business Use Cases

Domain Scenario
Sales Rank reps by revenue, allowing ties for shared bonuses
Education Rank students by exam score with shared placements
Manufacturing Rank suppliers by defect rate

Common Mistakes

Best Practices

Engineering Notes

RANK() and DENSE_RANK() share the same sorting cost as ROW_NUMBER() but additionally require a tie-comparison against the previous row’s ORDER BY value, evaluated during the same single pass.

Practice Questions

  1. Assign rank to employees ordered by emp_id.
  2. Show employee name and rank.
  3. Show the employee with rank = 1.
  4. Show the top 3 ranked employees.
  5. Compare ROW_NUMBER() and RANK() side by side on manager_id.

Difficulty

Beginner

Estimated Time

20–25 minutes

Learning Outcomes

Next Topic

03_DENSE_RANK


Lesson Navigation

← Previous: 01_ROW_NUMBERModule README → Next: 03_DENSE_RANK