Bird
0
0

Given two tables:

hard📝 Application Q8 of 15
SQL - Set Operations
Given two tables:
managers (id, name, department)
consultants (id, name, department)
Write a SQL query to retrieve all distinct names from both tables who belong to the 'Marketing' department, sorted by name in descending order.
ASELECT name FROM managers WHERE department = 'Marketing' UNION SELECT name FROM consultants WHERE department = 'Marketing' ORDER BY name DESC;
BSELECT name FROM managers UNION SELECT name FROM consultants WHERE department = 'Marketing' ORDER BY name DESC;
CSELECT name FROM managers WHERE department = 'Marketing' UNION ALL SELECT name FROM consultants WHERE department = 'Marketing' ORDER BY name DESC;
DSELECT name FROM managers WHERE department = 'Marketing' INTERSECT SELECT name FROM consultants WHERE department = 'Marketing' ORDER BY name DESC;
Step-by-Step Solution
Solution:
  1. Step 1: Filter each table by department

    Use WHERE department = 'Marketing' in both SELECT statements.
  2. Step 2: Combine results with UNION

    Use UNION to get distinct names from both tables.
  3. Step 3: Sort the combined result

    Apply ORDER BY name DESC once after the UNION.
  4. Step 4: Analyze options

    SELECT name FROM managers WHERE department = 'Marketing' UNION SELECT name FROM consultants WHERE department = 'Marketing' ORDER BY name DESC; correctly applies filters, uses UNION, and orders results.
    SELECT name FROM managers UNION SELECT name FROM consultants WHERE department = 'Marketing' ORDER BY name DESC; misses filtering on managers.
    SELECT name FROM managers WHERE department = 'Marketing' UNION ALL SELECT name FROM consultants WHERE department = 'Marketing' ORDER BY name DESC; uses UNION ALL which includes duplicates.
    SELECT name FROM managers WHERE department = 'Marketing' INTERSECT SELECT name FROM consultants WHERE department = 'Marketing' ORDER BY name DESC; uses INTERSECT which returns only common names.
  5. Final Answer:

    Option A -> Option A
  6. Quick Check:

    Filter both tables, UNION, then ORDER BY [OK]
Quick Trick: Filter before UNION; ORDER BY once after [OK]
Common Mistakes:
MISTAKES
  • Not filtering both tables before UNION
  • Using UNION ALL instead of UNION for distinct results
  • Placing ORDER BY inside individual SELECTs

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More SQL Quizzes