Skip to content

Commit d739b7f

Browse files
committed
understanding rank and dense rank function
1 parent f4d1e77 commit d739b7f

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
use world;
2+
3+
show tables;
4+
5+
select * from city;
6+
7+
-- rank and dense rank function are used to give the rank to each row according to the order by clause for the rows
8+
-- order by is required but partition by is optional
9+
10+
-- difference between rank and dense rank is that if the values are equal means rows order are equal then rank will skip the value but dense rank will not
11+
-- for eg: for rank: 1, 1, 3 (here rank 2 is missed) for dense_rank: 1, 1, 2 (here 2 is given)
12+
13+
-- find the second highest population
14+
-- if the two countries have equal population then rank will not work so we will use dense_rank
15+
16+
with results as(
17+
select name, countryCode,
18+
DENSE_RANK() over (order by population desc ) as rank_order
19+
from city)
20+
21+
select * from results where rank_order = 2;
22+
23+
-- now getting the all the cities according to the country code means for each country
24+
25+
with results as (
26+
select name, countryCode, population,
27+
DENSE_RANK() over (partition by countryCode order by population desc) as rank_order
28+
from city
29+
)
30+
31+
select * from results where rank_order = 2 order by countryCode;
32+

0 commit comments

Comments
 (0)