DELAPARRA
Index
Color
NL
Category: SQL

RANK / DENSE_RANK

Explained by Updated

What is RANK / DENSE_RANK?

RANK / DENSE_RANK: Rank rows by an ORDER BY. RANK leaves gaps after ties (1,1,3); DENSE_RANK does not (1,1,2). RANK() and DENSE_RANK() number rows by an ordering, such as highest score first. They differ in how they treat ties. With scores 90, 90 and 80, RANK gives 1, 1, 3, skipping a number after the tie; DENSE_RANK gives 1, 1, 2.

Definition source Coders Lingo, CC BY 4.0

Frequently asked questions about RANK / DENSE_RANK

How is RANK / DENSE_RANK used in practice?

They are window functions, used with OVER (ORDER BY ...), and can be combined with PARTITION BY to rank within groups, such as the best-selling products per category.

What should you keep in mind with RANK / DENSE_RANK?

Choose based on what the ranking means. For a sports-style ranking, RANK matches what people expect. For "the top three price levels", DENSE_RANK is usually right. When you need exactly one row per position with no ties, use ROW_NUMBER() instead. All three are available in MySQL 8, PostgreSQL and SQLite.

What does an example of RANK / DENSE_RANK look like?

SELECT name, score, RANK() OVER (ORDER BY score DESC) AS r, DENSE_RANK() OVER (ORDER BY score DESC) AS dr FROM players;

At a glance

CategorySQL
Explained by
Updated

More SQL terms

All terms starting with R

Skills

Download all skills (zip)

Manuals

Related services

Need any help?

Stuck on one of these in your own project? Tell me what you are working on and I will tell you how I would approach it.