Bird
0
0

You have two queries:

hard📝 Application Q9 of 15
PostgreSQL - Set Operations and Advanced Queries
You have two queries:
1) SELECT id, name FROM Employees WHERE department = 'HR'
2) SELECT id, name FROM Contractors WHERE department = 'HR'

You want to combine these queries to get all rows including duplicates. Which query achieves this?
ASELECT id, name FROM Employees WHERE department = 'HR' UNION SELECT id, name FROM Contractors WHERE department = 'HR';
BSELECT id, name FROM Employees WHERE department = 'HR' UNION ALL SELECT id, name FROM Contractors WHERE department = 'HR';
CSELECT id, name FROM Employees WHERE department = 'HR' INTERSECT SELECT id, name FROM Contractors WHERE department = 'HR';
DSELECT id, name FROM Employees WHERE department = 'HR' EXCEPT SELECT id, name FROM Contractors WHERE department = 'HR';
Step-by-Step Solution
Solution:
  1. Step 1: Understand requirement

    We want all rows from both queries including duplicates.
  2. Step 2: Choose correct operator

    UNION ALL combines results and keeps duplicates; UNION removes duplicates.
  3. Step 3: Analyze options

    SELECT id, name FROM Employees WHERE department = 'HR' UNION ALL SELECT id, name FROM Contractors WHERE department = 'HR'; uses UNION ALL, which fits the requirement.
  4. Final Answer:

    SELECT id, name FROM Employees WHERE department = 'HR' UNION ALL SELECT id, name FROM Contractors WHERE department = 'HR'; -> Option B
  5. Quick Check:

    Use UNION ALL to keep duplicates [OK]
Quick Trick: UNION ALL keeps duplicates, UNION removes them [OK]
Common Mistakes:
  • Using UNION instead of UNION ALL
  • Confusing INTERSECT or EXCEPT with UNION
  • Not matching column names and types

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes