SQL GROUP BY Practice: Counting Movies by Genre
Roll the catalog up by genre with GROUP BY, COUNT, and AVG.
Listing films is useful, but a shop owner usually wants a summary:
how deep is each genre, and how well does it rate? That is a job for
GROUP BY.
Grouping collapses many rows into one row per distinct value. Once the rows
are grouped by
genre, an aggregate like
count(*)
or
avg(rating)
runs once per group.
Every selected column is grouped or aggregated
The rule that trips people up: any column in the
SELECT
list must either appear in
GROUP BY
or sit inside an aggregate. Here
genre
is grouped, while
count(*)
and
avg(rating)
are aggregates.
select group_column,
count(*) as row_count,
round(avg(number_column), 2) as average
from table_name
group by group_column
order by row_count desc, group_column Schema · Movie Rentals Table · movies 5 columns · 12 rows
One row per movie in the catalog.
For each genre, return the genre, the number of films (movie_count), and the average rating rounded to two decimals (avg_rating). Sort by movie_count descending, then genre.
Run your query to inspect the result.
Expected answer
- Columns: genre, movie_count, avg_rating.
- Rows: 7 genres.
- Action leads the sort with 2 films and a 6.7 average.
Related
COUNT, SUM, AVG, MIN, MAX, GROUP BY, and HAVING.
COUNT, SUM, AVG, GROUP BY, and HAVING.
Practice aggregate reports, HAVING, and answer shape.
Avoid truncating fractional results.
Group or aggregate every selected column.
Practice buckets, business labels, and conditional counts.