Bird
0
0

You want to find all customers who have placed orders for products in the 'Electronics' category. Given tables:

hard📝 Application Q15 of 15
PostgreSQL - Subqueries in PostgreSQL
You want to find all customers who have placed orders for products in the 'Electronics' category. Given tables:
customers(id, name)
orders(id, customer_id, product_id)
products(id, name, category)
Which query correctly uses a subquery with IN to get these customers?
ASELECT name FROM customers WHERE id IN (SELECT id FROM products WHERE category = 'Electronics');
BSELECT name FROM customers WHERE id = IN (SELECT customer_id FROM orders WHERE product_id IN (SELECT id FROM products WHERE category = 'Electronics'));
CSELECT name FROM customers WHERE id IN (SELECT customer_id FROM orders WHERE product_id IN (SELECT id FROM products WHERE category = 'Electronics'));
DSELECT name FROM customers WHERE id IN (SELECT product_id FROM orders WHERE customer_id IN (SELECT id FROM products WHERE category = 'Electronics'));
Step-by-Step Solution
Solution:
  1. Step 1: Identify the correct subquery for products in 'Electronics'

    The innermost subquery selects product IDs where category is 'Electronics'.
  2. Step 2: Use these product IDs to find matching orders

    The middle subquery selects customer IDs from orders with those product IDs.
  3. Step 3: Select customer names whose IDs match those customer IDs

    The main query selects customer names where their ID is in the list from the orders subquery.
  4. Final Answer:

    SELECT name FROM customers WHERE id IN (SELECT customer_id FROM orders WHERE product_id IN (SELECT id FROM products WHERE category = 'Electronics')); -> Option C
  5. Quick Check:

    Nested IN subqueries filter customers by product category [OK]
Quick Trick: Use nested IN subqueries to filter step-by-step [OK]
Common Mistakes:
  • Using = IN instead of IN
  • Mixing up customer_id and product_id columns
  • Selecting wrong columns in subqueries

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes