Kathuko › SQL › Part 8: Top-N and paging

8.3 19c+

Practice: top-n twice

Two top-n problems. Expected rows first, answers behind a tap.

1. Chennai's last three matches

Chennai Comets' three most recent matches: date, opponent, and W, L or T.

Expected result · 3 rows
MATCH_DATEOPPONENTRESULT
2026-05-07LDSL
2026-04-30DBNW
2026-04-16LDSL
Try itShow the answer
select to_char(m.match_date, 'YYYY-MM-DD') as match_date,
       o.team_code as opponent,
       case when m.winner_id is null then 'T' when m.winner_id = 2 then 'W' else 'L' end as result
from   cr_matches m
join   cr_teams o on o.team_id = case when m.home_team_id = 2 then m.away_team_id else m.home_team_id end
where  2 in (m.home_team_id, m.away_team_id)
order  by m.match_date desc
fetch  first 3 rows only;
select match_date, opponent, result
from   (select to_char(m.match_date, 'YYYY-MM-DD') as match_date,
               o.team_code as opponent,
               case when m.winner_id is null then 'T' when m.winner_id = 2 then 'W' else 'L' end as result
        from   cr_matches m
        join   cr_teams o on o.team_id = case when m.home_team_id = 2 then m.away_team_id else m.home_team_id end
        where  2 in (m.home_team_id, m.away_team_id)
        order  by m.match_date desc)
where  rownum <= 3;

Their last match was the 2026 final, lost to Leeds by six wickets. Chennai won the 2025 final the same way, so call it even. (Team 2 is Chennai; page 0.3 has the team ids.)

2. The highest total of each season, ties included

For each season, the highest innings total, and every innings that matched it.

Expected result · 3 rows
SEASONMATCH_IDINNINGS_NOTOTAL
2025101194
2025102194
2026241207
Try itShow the answer
select s.season, x.match_id, x.innings_no, x.total
from   (select distinct season from cr_matches) s
cross  apply (select b.match_id, b.innings_no, sum(b.total_runs) as total
              from   cr_balls_v b
              where  b.season = s.season
              group  by b.match_id, b.innings_no
              order  by total desc
              fetch  first 1 row with ties) x
order  by s.season, x.match_id, x.innings_no;
select season, match_id, innings_no, total
from   (select b.season, b.match_id, b.innings_no, sum(b.total_runs) as total,
               rank() over (partition by b.season order by sum(b.total_runs) desc) as rnk
        from   cr_balls_v b
        group  by b.season, b.match_id, b.innings_no)
where  rnk = 1
order  by season, match_id, innings_no;

2025's best is a tie with itself: match 10, both innings 194, the tied match. FETCH FIRST on its own works on the whole result; inside CROSS APPLY (or LATERAL) it runs once per season.

Part 8 quiz

5 questions on all of Part 8. Get 4 right to pass. Retake it as often as you like.