SQL Top-N Practice: A Most-Rented Movies Report
The capstone: one query that joins, groups, ranks, and trims to a Top-5 report.
Time to combine the whole chapter into one report. A "Top-N" query is a
staple of real analytics:
JOIN
to get readable labels,
GROUP BY
to aggregate,
ORDER BY
to rank, and
LIMIT
to keep only the leaders.
Joining to
movies
lets you group by
title
rather than an opaque
movie_id, so the finished report reads like something you would hand to a manager.
Rank with a stable tie-breaker
When two titles are rented the same number of times, the order between
them is arbitrary unless you say otherwise. Ordering by
times_rented
first, then
revenue, then
title
makes the Top-5 deterministic: the same five rows, in the same order,
every run. That matters the moment
LIMIT
decides who makes the cut.
select dim.label,
count(*) as events,
round(sum(fact.amount), 2) as total
from fact_table as fact
join dim_table as dim on fact.dim_id = dim.dim_id
group by dim.label
order by events desc, total desc, dim.label
limit 5 Schema · Movie Rentals Tables · rentals, movies 2 tables
One row per rental. Movies still out have a null returned_date.
One row per movie in the catalog.
Build a Top-5 most-rented report: return each movie title, its number of rentals (times_rented), and its total revenue rounded to two decimals. Rank by times_rented, then revenue, then title, and keep only the top five.
Run your query to inspect the result.
Expected answer
- Columns: title, times_rented, revenue.
- Rows: 5, the top-rented titles.
- The Long Night leads with 4 rentals and 19.96 revenue.
That's the last lesson in “Applied Practice: Movie Rentals.”
The next chapter builds on what this one covered.
Start Chapter 13: Applied Practice: Website Analytics → Begins with 13.1 Sessions by channelRelated
Nested SELECTs, IN, EXISTS, and correlation.
Ranking, LAG/LEAD, and running totals at a glance.
Practice ranking, running totals, and top row per group.
The default RANGE frame groups tied rows; use ROWS.
Filter window results in a CTE or with QUALIFY.
The WITH clause, chained steps, and CTE vs subquery.