Brightlane's catalogue team wants to see every category alongside any products assigned to it — including categories that currently have no products.
Write a query to return the category name and product name for every category. Empty categories should still appear, with the product column missing.
Assumptions:
- The
categoriestable contains every defined category. - The
productstable contains every product in the catalogue;category_idon each product points to a category. - The result is anchored on the categories side — every category appears, including those with no matching products.
Output:
- One row per category-product pair, plus one row per empty category, with columns
category_nameandproduct_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
cat.name AS category_name,
p.name AS product_name
FROM
products p
RIGHT JOIN categories cat ON p.category_id = cat.id The shape
categories is the table that has to be enumerated in full — including the two empty ones, Clothing and Home & Garden. RIGHT JOIN preserves the right-side table, so writing products RIGHT JOIN categories keeps every category and fills product_name with NULL for the categories that have no products.
Clause by clause
SELECT cat.name AS category_name, p.name AS product_namereturns the category's name from the preserved right side and the product's name from the left side. For empty categories,p.nameisNULL— that's the unmatched signal.FROM products pis the left table. With aRIGHT JOIN, the left side is the one that may lose rows: a product whosecategory_iddoesn't match any category incategorieswould drop out, but in this schema every product has a real category, so nothing is dropped on the left.RIGHT JOIN categories cat ON p.category_id = cat.idflips the preservation direction. Every category appears at least once, regardless of whether any product points to it. The two empty categories appear as single rows withNULLinproduct_name.
Why this and not categories LEFT JOIN products
The two queries are equivalent. Swap the table order and change RIGHT JOIN to LEFT JOIN and you get the same result rows:
SELECT cat.name AS category_name, p.name AS product_name
FROM categories cat
LEFT JOIN products p ON cat.id = p.category_idMost analysts standardise on LEFT JOIN and arrange the tables so the one to preserve comes first. It reads more naturally — the anchor sits at the start of the FROM clause, where the eye lands. RIGHT JOIN exists in the SQL standard and shows up in legacy code, but it offers no expressive power that LEFT JOIN doesn't already have.
You practiced RIGHT JOIN and saw that it's just LEFT JOIN with the table order reversed. The recurring rule: any A LEFT JOIN B can be rewritten as B RIGHT JOIN A with identical results — most analysts standardise on LEFT JOIN because it reads more naturally.