Question

I'm trying to Write a SELECT statement that returns the category_name column from the Categories table and returns one row for each category that has never been assigned to a product in the Products table. there are four categories in the categories table and only three have been used in the products table. How do i make it show the one that hasn't been used? this is the code I've been trying, but it returns an empty result set.

select category_name
from categories c natural join products p
where not exists (
select category_name, category_id 
from categories c natural join products p);
Was it helpful?

Solution 2

Your query returns NULL because the subquery returns at least one row. Hence something exists. Juergen's answer shows how to do what you want with a left join. Here is how you solve the problem using not exists:

select c.category_name
from categories c
where not exists (select 1 from products p where p.category_id = c.category_id);

OTHER TIPS

Use a left join. I don't know your relation between those 2 tables but I assumed it is category.id and product.category_id

select c.category_name
from categories c 
left join products p on c.id = p.category_id
where p.category_id is null
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top