Wednesday, August 5, 2026

ROW_NUMBER(), RANK(), DENSE_RANK(), NTILE(), PERCENT_RANK(), CUME_DIST() In Sql

 SQL Window Ranking Functions – ROW_NUMBER(), RANK(), DENSE_RANK(), NTILE(), PERCENT_RANK(), CUME_DIST()

These are Window Functions (Analytic Functions) introduced in SQL Server to perform calculations across a set of rows without grouping them.

Unlike GROUP BY, window functions do not reduce the number of rows. Every row remains in the result.


Why do we need Ranking Functions?

Suppose you have an Employee table.

Employee
-------------------------------------
EmpId | Name   | Department | Salary
-------------------------------------
1     | John   | IT         | 80000
2     | David  | IT         | 90000
3     | Smith  | IT         | 90000
4     | Alice  | HR         | 60000
5     | Bob    | HR         | 70000
6     | Mike   | HR         | 70000
7     | Tom    | Sales      | 50000

Suppose interviewer asks

Find highest salary employee.

Easy.

SELECT *
FROM Employee
ORDER BY Salary DESC;

But what if interviewer asks

  • Highest salary employee in each department

  • Top 3 salaries

  • Second highest salary

  • Remove duplicate records

  • Pagination

  • Rank employees

That's where ranking functions are used.


Syntax

FunctionName()
OVER
(
    PARTITION BY column
    ORDER BY column
)

There are two important clauses.

ORDER BY

Mandatory.

Determines ranking order.

Example

ORDER BY Salary DESC

PARTITION BY

Optional.

Splits data into groups before assigning ranks.

Example

PARTITION BY Department

Means every department ranking starts from 1.


1. ROW_NUMBER()

Assigns a unique sequential number to every row.

Even if salaries are equal,
numbers are different.

Example

SELECT
Name,
Salary,
ROW_NUMBER() OVER(ORDER BY Salary DESC) AS RowNum
FROM Employee;

Output

NameSalaryROW_NUMBER
David900001
Smith900002
John800003
Bob700004
Mike700005
Alice600006
Tom500007

Notice

David and Smith have same salary.

Still

1
2

No ties.


Real-world use

Pagination

WITH CTE AS
(
SELECT *,
ROW_NUMBER() OVER(ORDER BY EmpId) RN
FROM Employee
)

SELECT *
FROM CTE
WHERE RN BETWEEN 11 AND 20;

This returns page 2.


Remove duplicates

Suppose duplicate emails exist.

WITH CTE AS
(
SELECT *,
ROW_NUMBER()
OVER(PARTITION BY Email ORDER BY EmpId) RN
FROM Customer
)

DELETE FROM CTE
WHERE RN>1;

Very common interview question.


2. RANK()

Assigns same rank to equal values.

But skips next rank.

Example

SELECT
Name,
Salary,
RANK() OVER(ORDER BY Salary DESC) RankNo
FROM Employee;

Output

NameSalaryRank
David900001
Smith900001
John800003
Bob700004
Mike700004
Alice600006
Tom500007

Notice

1
1
3

Rank 2 is skipped.

Because two employees share rank 1.


Visualization

90000
David     Rank 1

90000
Smith     Rank 1

80000
John      Rank 3

Rank 2 missing.


Use Case

Sports Competition

100 Marks
Student A

100 Marks
Student B

95 Marks
Student C

Ranks

1
1
3

Exactly like Olympics.


3. DENSE_RANK()

Similar to RANK()

But

No gaps.

Example

SELECT
Name,
Salary,
DENSE_RANK()
OVER(ORDER BY Salary DESC)
AS DenseRank
FROM Employee;

Output

NameSalaryDense Rank
David900001
Smith900001
John800002
Bob700003
Mike700003
Alice600004
Tom500005

Notice

1
1
2
3
3
4
5

No skipped numbers.


Visualization

90000
David     1

90000
Smith     1

80000
John      2

70000
Bob       3

70000
Mike      3

Difference between ROW_NUMBER(), RANK(), DENSE_RANK()

SalaryROW_NUMBERRANKDENSE_RANK
90000111
90000211
80000332
70000443
70000543
60000664

Visual Difference

ROW_NUMBER()

90000   1
90000   2
80000   3
70000   4
70000   5

RANK()

90000   1
90000   1
80000   3
70000   4
70000   4
60000   6

DENSE_RANK()

90000   1
90000   1
80000   2
70000   3
70000   3
60000   4

Which one should you use?

Need unique row number?

Use

ROW_NUMBER()

Examples

  • Pagination

  • Duplicate removal

  • Unique numbering


Need competition ranking?

Use

RANK()

Examples

  • Sports

  • Exam Ranking


Need consecutive ranking?

Use

DENSE_RANK()

Examples

  • Top N salaries

  • Product Ranking

  • Customer Ranking


PARTITION BY Example

Suppose

IT

John    80000
David   90000
Smith   90000

HR

Alice   60000
Bob     70000
Mike    70000

Query

SELECT
Department,
Name,
Salary,
DENSE_RANK()
OVER
(
PARTITION BY Department
ORDER BY Salary DESC
)
AS Rank
FROM Employee;

Output

DeptNameSalaryRank
ITDavid900001
ITSmith900001
ITJohn800002
HRBob700001
HRMike700001
HRAlice600002

Notice ranking restarts for every department.


4. NTILE()

Splits rows into equal-sized groups (buckets).

Example

SELECT
Name,
Salary,
NTILE(4)
OVER(ORDER BY Salary DESC)
AS Quartile
FROM Employee;

If there are 20 rows,

Quartile 1

Top 25%

Quartile 2

Next 25%

Quartile 3

Next

Quartile 4

Lowest

Used in

  • Salary bands

  • Performance categories

  • Customer segmentation


5. PERCENT_RANK()

Returns the relative rank of a row as a value between 0 and 1.

Formula:

(RANK - 1) / (TotalRows - 1)

Example

SELECT
Name,
Salary,
PERCENT_RANK() OVER(ORDER BY Salary DESC) AS PercentRank
FROM Employee;

Sample output

NameSalaryPercentRank
David900000.00
Smith900000.00
John800000.33
Bob700000.50
Mike700000.50
Alice600000.83
Tom500001.00

Use cases:

  • Percentile analysis

  • Academic grading

  • Sales performance evaluation


6. CUME_DIST()

Returns the cumulative distribution, i.e., the proportion of rows with values less than or equal to the current row.

Example

SELECT
Name,
Salary,
CUME_DIST() OVER(ORDER BY Salary DESC) AS CumulativeDist
FROM Employee;

Sample output

NameSalaryCUME_DIST
David900000.29
Smith900000.29
John800000.43
Bob700000.71
Mike700000.71
Alice600000.86
Tom500001.00

Use cases:

  • Finding top performers

  • Statistical analysis

  • Distribution reporting


Common Interview Questions

1. Find the second highest salary.

Using DENSE_RANK():

WITH SalaryRank AS
(
    SELECT *,
           DENSE_RANK() OVER(ORDER BY Salary DESC) AS SalaryRank
    FROM Employee
)
SELECT *
FROM SalaryRank
WHERE SalaryRank = 2;

2. Find the top 3 highest salaries.

WITH SalaryRank AS
(
    SELECT *,
           DENSE_RANK() OVER(ORDER BY Salary DESC) AS SalaryRank
    FROM Employee
)
SELECT *
FROM SalaryRank
WHERE SalaryRank <= 3;

3. Find the highest-paid employee in each department.

WITH DeptRank AS
(
    SELECT *,
           DENSE_RANK() OVER(
               PARTITION BY Department
               ORDER BY Salary DESC
           ) AS DeptRank
    FROM Employee
)
SELECT *
FROM DeptRank
WHERE DeptRank = 1;

4. Remove duplicate rows.

WITH DuplicateRows AS
(
    SELECT *,
           ROW_NUMBER() OVER(
               PARTITION BY Email
               ORDER BY EmpId
           ) AS RN
    FROM Customer
)
DELETE FROM DuplicateRows
WHERE RN > 1;

5. Implement pagination (rows 21–30).

WITH OrderedEmployees AS
(
    SELECT *,
           ROW_NUMBER() OVER(ORDER BY EmpId) AS RN
    FROM Employee
)
SELECT *
FROM OrderedEmployees
WHERE RN BETWEEN 21 AND 30;

Quick Summary

FunctionDuplicates Get Same Rank?Gaps in Ranking?Common Use Cases
ROW_NUMBER()❌ No❌ NoPagination, duplicate removal, unique sequencing
RANK()✅ Yes✅ YesCompetition ranking, exam results
DENSE_RANK()✅ Yes❌ NoTop N salaries, leaderboards
NTILE(n)N/AN/ADivide rows into equal groups or quartiles
PERCENT_RANK()Based on RANK()May reflect rank gapsPercentile calculations
CUME_DIST()Includes ties togetherN/ACumulative distribution and statistical reporting

Interview Tip

A very common interview question is:

"What is the difference between ROW_NUMBER(), RANK(), and DENSE_RANK()?"

A concise answer:

  • ROW_NUMBER() gives every row a unique sequential number, even when values are tied.

  • RANK() assigns the same rank to tied rows but skips the next rank(s).

  • DENSE_RANK() assigns the same rank to tied rows without leaving gaps.

Understanding these differences, along with PARTITION BY and ORDER BY, is essential for solving real-world SQL problems such as pagination, leaderboards, Top-N queries, duplicate removal, and departmental rankings.

Technical Lead Scenario-Based Interview Questions & Answers (.NET Core + Azure)

Technical Lead Scenario-Based Interview Questions & Answers (.NET Core + Azure)


Scenario 1: Designing a New Enterprise Application

Interviewer

Your company wants to build a Loan Management System used by 500,000 customers. How would you design the architecture?

Expected Answer

First I gather functional and non-functional requirements.

Functional:

  • Customer Registration

  • Loan Application

  • Approval Workflow

  • Payment

  • Notifications

Non-functional:

  • High Availability

  • Scalability

  • Security

  • Performance

  • Disaster Recovery

Architecture:

Angular

      |

API Gateway (Azure APIM)

      |

-----------------------------

Identity Service

Loan Service

Payment Service

Notification Service

Document Service

-----------------------------

Azure Service Bus

Azure SQL

Blob Storage

Redis Cache

Application Insights

Patterns:

  • Clean Architecture

  • DDD

  • CQRS

  • Repository

  • Unit of Work

  • Event Driven

Azure Services

  • Azure App Service

  • Azure SQL

  • Azure Key Vault

  • Azure Service Bus

  • Azure Storage

  • Azure Monitor

  • Application Insights

This architecture supports independent deployment and scaling.


Scenario 2: Microservice Communication

Interviewer

Service A needs customer details from Service B.

Would you call it synchronously or asynchronously?

Answer

Depends on business requirement.

If immediate response required

Order Service

↓

Customer Service (REST API)

Use:

  • REST

  • gRPC

If eventual consistency acceptable

Order Created

↓

Azure Service Bus

↓

Customer Service

↓

Notification Service

↓

Audit Service

Benefits

  • Loose coupling

  • Retry

  • High availability

  • Independent scaling


Scenario 3: API Performance Issue

Interviewer

One API takes 18 seconds.

How will you investigate?

Answer

My investigation sequence:

Step 1

Application Insights

Check

  • Dependency calls

  • Exceptions

  • Slow SQL

Step 2

Database

Check

Execution Plan

Missing Index

Blocking

Deadlock

Step 3

Code

Look for

foreach(...)
{
   await repository.GetById();
}

N+1 problem.

Instead

Single Query

Step 4

Caching

Redis

Memory Cache

Step 5

Load Testing

Azure Load Test

JMeter

Finally optimize.


Scenario 4: Production is Down

Interviewer

Production suddenly becomes unavailable.

What do you do?

Answer

Never panic.

Follow Incident Process.

Step 1

Verify

Azure Health

App Service

SQL

Service Bus

Step 2

Rollback if deployment caused issue.

Step 3

Collect Logs

Application Insights

Azure Monitor

Step 4

Temporary Fix

Scale Out

Restart unhealthy instances

Disable problematic feature

Step 5

Root Cause Analysis

Document

Prevent recurrence.


Scenario 5: Azure SQL Database Reaches 100% CPU

Interviewer

Users complain application is slow.

Azure SQL CPU is 100%.

How do you solve it?

Answer

Check

Top Queries

Execution Plans

Missing Indexes

Deadlocks

Blocking Sessions

Large Table Scan

Optimize

Indexes

Pagination

Caching

Read-only replicas

Partitioning

Increase DTU/vCore only if required.


Scenario 6: Team Writes Duplicate Logic

Interviewer

Every developer writes validation differently.

What will you do?

Answer

As Technical Lead

I introduce

  • Coding Standards

  • Common Validation Library

  • Reusable NuGet Package

  • Static Code Analysis

  • Pull Request Guidelines

Every PR goes through review.

Consistency improves.


Scenario 7: Security Review

Interviewer

Security team found secrets inside appsettings.json.

How do you fix it?

Answer

Never store secrets.

Move

Connection String

API Keys

Certificates

Passwords

To

Azure Key Vault

Use

Managed Identity

Benefits

  • Secret Rotation

  • Encryption

  • Audit Trail


Scenario 8: API Authentication

Interviewer

How do you secure APIs?

Answer

Authentication

Azure AD

JWT

Authorization

Role Based Access

Policy Based Authorization

Claims

Other security

HTTPS

Rate Limiting

Input Validation

OWASP

Key Vault

APIM


Scenario 9: Scaling

Interviewer

Traffic increases 20 times during Black Friday.

How will your application survive?

Answer

Use

Stateless APIs

Redis Cache

Autoscaling

Azure App Service Scale Out

Azure SQL Elastic Pool

Azure Service Bus

CDN

Blob Storage

Horizontal scaling.


Scenario 10: Event Driven Architecture

Interviewer

Customer places an order.

Five services need notification.

How will you design?

Answer

Instead of

Order

↓

Inventory

↓

Payment

↓

Email

↓

Analytics

↓

CRM

Use

Order Service

↓

Publish Event

↓

Azure Service Bus Topic

↓

Inventory

↓

Payment

↓

Email

↓

Analytics

↓

CRM

Much more scalable.


Scenario 11: Code Review

Interviewer

What do you check during code review?

Answer

I check

✔ SOLID

✔ Naming

✔ Security

✔ Performance

✔ Exception Handling

✔ Logging

✔ Unit Tests

✔ Async

✔ Disposal

✔ SQL Injection

✔ Reusability


Scenario 12: Logging Strategy

Interviewer

How do you implement logging?

Answer

Levels

Information

Warning

Error

Critical

Use

ILogger

Serilog

Application Insights

Correlation ID

Never log passwords.


Scenario 13: Production Bug

Interviewer

A bug exists only in Production.

Not reproducible locally.

How do you investigate?

Answer

Check

Logs

Telemetry

Configuration

Environment Variables

Version

Feature Flags

Data Differences

Database

Application Insights Transaction Search.


Scenario 14: API Versioning

Interviewer

Old clients still use v1.

New features in v2.

How do you support both?

Answer

api/v1/customer

api/v2/customer

Deprecate older versions gradually.

Communicate timeline.


Scenario 15: CI/CD

Interviewer

Explain your deployment pipeline.

Answer

Developer

↓

Git

↓

Pull Request

↓

Build

↓

Unit Test

↓

SonarQube

↓

Publish Artifact

↓

Deploy Dev

↓

QA

↓

UAT

↓

Production Approval

↓

Production


Scenario 16: Production Deployment Failed

Interviewer

Half deployment completed.

Users affected.

Now what?

Answer

Blue-Green Deployment

Rollback

Database backward compatibility

Feature Flags

Health Check

Smoke Test


Scenario 17: Team Conflict

Interviewer

Two senior developers disagree on architecture.

What do you do?

Answer

Arrange technical discussion.

Compare

Performance

Maintainability

Scalability

Security

Development effort

Prototype if needed.

Decision based on facts.

Not opinions.


Scenario 18: Slow Microservice

Interviewer

One service delays every request.

Answer

Check

Dependency Calls

Database

Redis

Thread Pool

Memory

GC

CPU

Distributed Tracing

Application Insights


Scenario 19: Legacy Monolith Migration

Interviewer

Company wants Microservices.

How will you migrate?

Answer

Use

Strangler Pattern

Extract modules one by one

Customer

Order

Payment

Notification

Eventually retire monolith.


Scenario 20: Observability

Interviewer

How do you monitor application health?

Answer

Metrics

CPU

Memory

Response Time

Availability

Dependency Failures

Exception Rate

Dashboard

Azure Monitor

Application Insights

Alerts

Teams

Email

SMS


Scenario 21: Handling High Traffic During a Flash Sale

Interviewer

Your e-commerce site receives 10x normal traffic during a flash sale. Checkout APIs start timing out. What immediate and long-term actions would you take?

Answer

Immediate actions:

  • Scale out Azure App Service instances.

  • Increase Azure SQL compute if it's the bottleneck.

  • Enable/verify Redis caching for frequently accessed data.

  • Queue non-critical operations (emails, analytics) using Azure Service Bus.

  • Monitor live metrics in Application Insights.

Long-term improvements:

  • Optimize slow database queries and indexing.

  • Implement autoscaling rules.

  • Use CDN for static content.

  • Add load testing to CI/CD.

  • Introduce asynchronous processing where appropriate.


Scenario 22: Production Memory Leak

Interviewer

After a few days of uptime, your API becomes slow and eventually crashes with OutOfMemoryException. How do you investigate?

Answer

  • Check Application Insights memory metrics.

  • Capture memory dumps.

  • Analyze with Visual Studio Diagnostic Tools or dotMemory.

  • Look for:

    • Undisposed IDisposable objects.

    • Static collections growing indefinitely.

    • Event handler leaks.

    • Large object allocations.

  • Fix resource disposal and validate with load testing.


Scenario 23: Breaking Database Schema Changes

Interviewer

A database schema change is required, but older application versions are still running during deployment. How do you avoid downtime?

Answer

  • Follow backward-compatible database changes.

  • Add new columns before removing old ones.

  • Deploy application changes that support both schemas.

  • Migrate data in the background.

  • Remove deprecated schema only after all instances are updated.


Scenario 24: Third-Party API Failure

Interviewer

Your payment provider is intermittently unavailable. How do you prevent your application from failing?

Answer

Use resilience patterns:

  • Retry with exponential backoff.

  • Circuit Breaker.

  • Timeout policies.

  • Fallback responses where appropriate.

  • Queue requests if business rules allow.

  • Monitor failures and alert operations.

Common implementation: Polly in .NET.


Scenario 25: Mentoring a Junior Team

Interviewer

A junior developer repeatedly introduces bugs. As a Technical Lead, how do you handle it?

Answer

  • Review the code together instead of only rejecting PRs.

  • Explain the reasoning behind feedback.

  • Pair program on complex features.

  • Recommend learning resources.

  • Gradually increase responsibility.

  • Track improvement through regular one-on-one sessions.

This approach improves both code quality and team growth.


Technical Lead Interview Tips

Interviewers also evaluate how you think, not just what you know. When answering scenario questions:

  1. Clarify assumptions before proposing a solution.

  2. Consider scalability, security, performance, and maintainability together.

  3. Mention trade-offs and why you chose a particular approach.

  4. Include Azure services, design patterns, and DevOps practices where relevant.

  5. Explain how you would communicate with stakeholders and lead the team during incidents.

These scenarios closely reflect the responsibilities you listed and are typical of Technical Lead interviews for enterprise .NET and Azure roles.

Don't Copy

Protected by Copyscape Online Plagiarism Checker