Scenario: Brightlane's catalog team is verifying which product categories are actively used across the catalog — categories with at least one assigned product.
Task: Write a query to return the id and name of every category that has at least one product assigned to it.
Assumptions:
- The result covers only categories that appear as the
category_idof at least one product.
Output:
- One row per qualifying category.
- Columns in this order:
category_id,category_name.
Schema · ecommerce 5 tables
Run previews · Check grades
Write a query, then run it to see results here.
Worked solution Try it yourself first
SELECT
c.id AS category_id,
c.name AS category_name
FROM
categories c
WHERE
EXISTS (
SELECT
1
FROM
products p
WHERE
p.category_id = c.id
) The shape
The question is existence, not value. For each category, is there at least one product on file? EXISTS answers that with a correlated subquery — return the category as soon as one matching product is found, and stop looking.
Clause by clause
SELECT c.id AS category_id, c.name AS category_namereturns the identifying columns from the parent side.FROM categories cis the parent set. Every category is a candidate until the existence check filters it.WHERE EXISTS (...)keeps a category only when the inner subquery returns at least one row. The subquery returns rows whenever a product'scategory_idmatches the current category'sid, so the filter passes whenever the category has any product on file.- Inside the subquery,
SELECT 1is a placeholder.EXISTScares only about whether any row comes back; it never inspects the projected value. WritingSELECT 1makes the intent explicit.
Why this and not a join with DISTINCT
Joining categories to products and then applying DISTINCT produces the same set of categories, but the join first multiplies each category by every matching product before the deduplication collapses it back down. EXISTS short-circuits on the first match per category, which is both cleaner to read and the structural shape the problem is testing.
You practiced the existence-check pattern — keeping a parent only when at least one matching child is on record.