Bird
0
0

Given the tables products(id, category_id, price) and categories(id, name), which query will return the same results but likely with better performance?

medium📝 query result Q5 of 15
SQL - Subqueries
Given the tables products(id, category_id, price) and categories(id, name), which query will return the same results but likely with better performance?

Query A:
SELECT p.id FROM products p WHERE p.category_id IN (SELECT c.id FROM categories c WHERE c.name = 'Electronics');
Query B:
SELECT p.id FROM products p JOIN categories c ON p.category_id = c.id WHERE c.name = 'Electronics';
AQuery A, because subqueries are simpler to execute.
BQuery B, because JOINs allow the optimizer to use indexes efficiently.
CBoth queries perform identically in all cases.
DQuery A, because it avoids the overhead of JOIN operations.
Step-by-Step Solution
Solution:
  1. Step 1: Understand the IN subquery version

    The IN subquery version uses a subquery with IN(), which may be less efficient on large datasets.
  2. Step 2: Understand the JOIN version

    The JOIN version uses a JOIN, which databases optimize well, especially with indexes on join columns.
  3. Final Answer:

    Query B, because JOINs allow the optimizer to use indexes efficiently. -> Option B
  4. Quick Check:

    JOIN with indexes = better performance [OK]
Quick Trick: JOINs leverage indexes better than subqueries [OK]
Common Mistakes:
MISTAKES
  • Assuming subqueries are always simpler and faster
  • Ignoring the role of indexes in JOIN performance
  • Believing IN() subqueries scale well always

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More SQL Quizzes