Distinct Product Categories

An easy SQL interview practice problem on DataDriven. Write the query and run it against a real database, with instant feedback.

Domain
SQL
Difficulty
easy
Seniority
L3
Asked in
Google

Problem

We're rebuilding our product taxonomy from the products table and need every category that appears on any product, each one listed once.

A quick category inventory.

Tables

products

Columns: product_id INTEGER, product_name TEXT, category TEXT, price REAL, rating REAL, in_stock INTEGER

products: 10 of 200 rows
product_idproduct_namecategorypriceratingin_stock
1001Basic Device 1XBooks17.522.71
1050Deluxe Bundle 2XClothing25.054.41
1099Pro Unit 3XHome & Kitchen32.582.11
1148Ultra Tool 4XCollectibles40.113.81
1197Essential Set 5XToys47.641.51
1246Classic System 6XBeauty03.21
1295Smart Gadget 7XAutomotive62.74.90
1344Eco Kit 8XGarden70.232.61
1393Turbo Pack 9XMusic77.764.30
1442Premium Widget 10XElectronics85.2921

Expected output

First 5 of 11 rows
category
Books
Clothing
Home & Kitchen
Collectibles
Toys

Worked solution and explanation

This is a set extraction dressed up as a taxonomy request. products holds one row per product, and the ask is the set of category values, not the rows. Anyone finds the category column. What separates candidates is saying the grain out loud before typing: a bare SELECT category FROM products returns 200 rows on this data for 11 real categories, so merchandising gets a taxonomy where 'Books' shows up twenty times.

Getting from rows to values

Step 1: Name the grain of products

product_id is unique, category is not. Most categories sit on 20 products, Sports on 18, and 'Collectibles' on just two. The table is product-grain, so the answer has to change grain to one row per category.

Step 2: Collapse on category alone

Project only category and deduplicate. The dedup applies to everything in the select list, so any second column you add (product_name, price) makes the pair unique again and you are back to 200 rows.

Step 3: Keep every category, stocked or not

Every 'Music' product has in_stock = 0. A reflexive WHERE in_stock = 1 to mean 'what we sell' quietly returns 10 categories instead of 11. The taxonomy covers every category on any product, so no row filter belongs here.

One row per category
SELECT DISTINCT category
FROM products
Dedup the values
SELECT DISTINCT category says exactly what is asked: the set of values. It is the form to reach for when nothing is computed per category.
Group the values
GROUP BY category returns the same 11 rows and usually the same plan. It earns its place the moment a follow-up wants COUNT(*) per category next to the name.

Common follow-up questions