SQL tricks
November 26, 2022

How get most represented record in table

On Sakila Database we have table category represented categories of movies in DB and table film_category where each film linked it it's category (one film can be present in more then one category).

We need to determinate most popular movie category in a library.
First of all we can group table film_category by category_id field and apply COUNT(*) function:

select category_id, count(*)
from film_category
group by category_id;

After that we can get most popular category by apply ORDER and LIMIT statement to previous query:

select category_id
from film_category
group by category_id
order by count(*) desc
limit 1;

So we got most popular category_id. Now we can get the category name:

select name from category where category_id = 
(select category_id
from film_category
group by category_id
order by count(*) desc
limit 1);

The above query is only one of possible solutions. You can try it online on SQLIZE.online

You also can find your own solution and post it in comments after this article!