EbrahemSamer's avatar

How to use SQL to select categories that have products in it ?

I've categories table

id - category_name

and products table

id - product_name - category_id

I want to get all categories that have products in it using sql query

0 likes
2 replies
tykus's avatar
tykus
Best Answer
Level 104
select *
from `categories`
where exists (
    select * from `products` where `categories`.`id` = `products`.`category_id`
);

or

select *
from categories
left join (select category_id, count(id) as product_count from products group by category_id) as temp
on category_id = categories.id 
where product_count > 0;
1 like
MichalOravec's avatar

This should be enough

select categories.*
from categories
join products on products.category_id = categories.id
1 like

Please or to participate in this conversation.