🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

ROW_NUMBER, RANK, and DENSE_RANK

Window FunctionsRanking FunctionsđŸŸĸ Free Lesson
Window Functions

ROW_NUMBER, RANK, and DENSE_RANK

Three ranking functions with critical differences in how they handle ties.

  • ROW_NUMBER — Unique sequential integers, no ties
  • RANK — Ties share a rank, gaps follow tied groups
  • DENSE_RANK — Ties share a rank, no gaps in numbering Choosing the right function depends on whether gaps in ranking matter.

The Three Ranking Functions

Visual Comparison

SalaryROW_NUMBERRANKDENSE_RANK$90,000111$85,000222$85,000 (tie)322$75,000443← No gap
RowSalaryROW_NUMBERRANKDENSE_RANK
A90000111
B85000222
C85000322
D80000443
E75000554

Notice how ROW_NUMBER assigns unique numbers even to ties, RANK skips to 4 after the tie at 2, and DENSE_RANK stays sequential.

Core Syntax

-- All three ranking functions side by side
SELECT
    employee_name,
    department,
    salary,
    ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS row_num,
    RANK()       OVER (PARTITION BY department ORDER BY salary DESC) AS rank_val,
    DENSE_RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS dense_rank_val
FROM employees;

ROW_NUMBER — Unique Ordering

-- Select the most recent order per customer
WITH ranked_orders AS (
    SELECT
        customer_id,
        order_id,
        order_date,
        order_amount,
        ROW_NUMBER() OVER (
            PARTITION BY customer_id
            ORDER BY order_date DESC
        ) AS rn
    FROM orders
)
SELECT customer_id, order_id, order_date, order_amount
FROM ranked_orders
WHERE rn = 1;
-- Deduplicate: keep only the latest record per student
WITH deduplicated AS (
    SELECT
        student_id,
        course_name,
        grade,
        submission_date,
        ROW_NUMBER() OVER (
            PARTITION BY student_id, course_name
            ORDER BY submission_date DESC
        ) AS rn
    FROM student_submissions
)
SELECT student_id, course_name, grade, submission_date
FROM deduplicated
WHERE rn = 1;

RANK — Gaps After Ties

-- Competition results with RANK (ties share rank, gaps follow)
SELECT
    contestant_name,
    score,
    RANK() OVER (ORDER BY score DESC) AS competition_rank
FROM contest_results
ORDER BY competition_rank;

-- Output:
-- Alice    | 98 | 1
-- Bob      | 95 | 2
-- Charlie  | 95 | 2
-- Diana    | 92 | 4   <-- Gap after the tie at rank 2

DENSE_RANK — No Gaps

-- Grade assignment with DENSE_RANK (no gaps after ties)
SELECT
    student_name,
    score,
    DENSE_RANK() OVER (ORDER BY score DESC) AS grade_rank,
    CASE
        WHEN DENSE_RANK() OVER (ORDER BY score DESC) <= 3 THEN 'Honors'
        WHEN DENSE_RANK() OVER (ORDER BY score DESC) <= 7 THEN 'Pass'
        ELSE 'Needs Improvement'
    END AS designation
FROM student_scores;

Practical Scenario: Top N Per Group

-- Top 3 earners in each department
WITH department_ranks AS (
    SELECT
        employee_name,
        department,
        salary,
        DENSE_RANK() OVER (
            PARTITION BY department
            ORDER BY salary DESC
        ) AS dept_rank
    FROM employees
)
SELECT employee_name, department, salary, dept_rank
FROM department_ranks
WHERE dept_rank <= 3
ORDER BY department, dept_rank;
-- Bottom 2 performers per department
WITH bottom_performers AS (
    SELECT
        employee_name,
        department,
        performance_score,
        ROW_NUMBER() OVER (
            PARTITION BY department
            ORDER BY performance_score ASC
        ) AS bottom_rank
    FROM employees
    WHERE performance_score IS NOT NULL
)
SELECT employee_name, department, performance_score
FROM bottom_performers
WHERE bottom_rank <= 2;

When to Use Each

ScenarioRecommendedWhy
PaginationROW_NUMBERNeed unique sequential IDs
DeduplicationROW_NUMBERPick exactly one row per group
Competition rankingRANKTies should be equal, gaps expected
Leaderboard displayDENSE_RANKClean numbering without gaps
Percentile assignmentNTILESplit into N equal groups

Combining with Other Window Functions

-- Full salary analysis with ranking and comparison
SELECT
    employee_name,
    department,
    salary,
    ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS row_num,
    RANK()       OVER (PARTITION BY department ORDER BY salary DESC) AS rank_val,
    DENSE_RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS dense_rank_val,
    LAG(salary)  OVER (PARTITION BY department ORDER BY salary DESC) AS prev_salary,
    salary - LAG(salary) OVER (PARTITION BY department ORDER BY salary DESC) AS gap_to_prev
FROM employees
ORDER BY department, row_num;

Extended Learning: Beyond the Basics

Key Concepts Summary

This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.

Prerequisite Knowledge

Before studying this topic in depth, ensure you understand:

  • Basic definitions and terminology
  • Core formulas and their derivations
  • Common applications in real-world scenarios
  • Typical pitfalls and misconceptions

Step-by-Step Walkthrough

Let us work through a complete example to solidify understanding:

Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.

Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.

Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.

Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.

Common Mistakes to Avoid

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. Forgetting constraints — Check that solutions satisfy all given conditions

Real-World Applications

Understanding this concept is essential for:

  • Advanced problem solving in examinations
  • Building intuition for more complex topics
  • Developing analytical thinking skills
  • Applying mathematical reasoning to practical situations

Practice Exercises

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. Challenge: Create your own problem that requires this concept plus additional knowledge.

Interview and Exam Tips

  • Common question patterns: Identify which exam or interview formats test this topic
  • Time management: Practice completing problems within time constraints
  • Common traps: Know the typical mistakes examiners set as distractors
  • Verification strategy: Develop a quick method to check your answer

Related Topics

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids errors

Further Reading

For students who want to go deeper:

  • Standard textbooks on the subject
  • Research papers applying this concept
  • Online courses with video explanations
  • Practice problem collections with detailed solutions
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert SQL Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement