What's the difference between RANK() and DENSE_RANK() functions in oracle?
Here is the skinny on RANK()
vs. DENSE_RANK()
. Both of these SQL functions assign rankings to rows within an ordered sequence. However, RANK()
skips the next rank after a tie (e.g., 1, 1, 3), while DENSE_RANK()
doesn't skip and continues ranking after a tie (e.g., 1, 1, 2).
So, use RANK()
if you don't mind leapfrog rankings and DENSE_RANK()
if you prefer a continuous, unbroken rank sequence.
Null-handling with RANK() and DENSE_RANK()
When sorting through the null-ness of space, both RANK()
and DENSE_RANK()
treat null values as equals. However, RANK()
can open black holes, creating substantial ranking gaps. To maintain a smoother, gapless ranking journey, DENSE_RANK()
or ROW_NUMBER()
is your co-pilot.
For, example, if you seek the cosmic "nth salary" with lots of null values and ties in your dataset, DENSE_RANK()
ensures a smooth voyage without wormholes, while RANK()
may send you into skipped rank-space areas.
Continuous vs. tier-based ranking
Ranks without gravity (gaps)
If you need sequential IDs or employee grades without levels, or maybe just ordered lists that despise skipped values, opt for DENSE_RANK()
.
Leapfrogging to the stars
On the flip side, if your analysis will benefit from recognizing performance tiers or maintaining distinct ranks, regardless of ties, use RANK()
.
Advanced Ranking Scenarios
Department-based ranking or "corporate galactic sectors"
For ranking within a database's own universe, like department, use OVER (PARTITION BY deptno ORDER BY sal)
to verify the performance within each microcosm.
Nulls pulling rank
Planets (nulls) in your ranking universe can cause ranking shifts, especially when using RANK()
. These could lead to unexpected results!
Choosing your spacecraft: RANK() or DENSE_RANK()?
- Expecting ties? Choose wisely.
- Will null entries skew your ranks?
- Need an unbroken sequence?
- Do you require distinct ranks even when tied?
Broadening your cosmic understanding
Supercharged data analysis
A solid understanding of the celestial bodies known as RANK()
and DENSE_RANK()
can sky-rocket your SQL data analysis effectiveness, especially when dealing with supernova-sized datasets.
The universe of ranks
Explore, compare, understand. Having a comprehensive grasp of ranking can take your data explorations to a whole new level.
To ROW_NUMBER() or not to ROW_NUMBER()
If you're in a UFO that needs a unique identifier per row, despite clones (ties), steer towards ROW_NUMBER()
. This function assigns a unique, incremental value per row, regardless of duplicates.
Was this article helpful?