Bird
0
0

You have two SELECT queries:

hard📝 Application Q8 of 15
PostgreSQL - Set Operations and Advanced Queries
You have two SELECT queries:
SELECT id FROM orders_2021;
and
SELECT id FROM orders_2022;
You want to get all unique IDs from both years but keep duplicates only from orders_2021. Which PostgreSQL set operation combination achieves this?
AUse <code>UNION ALL</code> between both queries and then <code>DISTINCT</code> on the result.
BUse <code>UNION ALL</code> and then remove duplicates only from the second query before union.
CUse <code>UNION ALL</code> and then subtract duplicates from the second query using <code>EXCEPT</code>.
DUse <code>UNION ALL</code> and then join with the first query to filter duplicates.
Step-by-Step Solution
Solution:
  1. Step 1: Understand the requirement

    Keep duplicates from orders_2021 but only unique rows from orders_2022 that are not in orders_2021.
  2. Step 2: Use EXCEPT to remove duplicates from second query

    SELECT id FROM orders_2022 EXCEPT SELECT id FROM orders_2021 returns unique IDs in 2022 not in 2021.
  3. Step 3: Combine with UNION ALL

    Then SELECT id FROM orders_2021 UNION ALL (previous EXCEPT result) keeps duplicates from 2021 and adds unique 2022 IDs.
  4. Final Answer:

    Use UNION ALL and then subtract duplicates from the second query using EXCEPT. -> Option C
  5. Quick Check:

    Check if duplicates only from first query remain [OK]
Quick Trick: Subtract duplicates from second query before UNION ALL [OK]
Common Mistakes:
  • Applying DISTINCT after UNION ALL removes all duplicates
  • Not removing duplicates from second query
  • Using JOIN which complicates the logic

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes