Bird
0
0

You have two tables:

hard📝 Application Q15 of 15
SQL - Set Operations
You have two tables:
Sales_2023: product_id, quantity_sold
Sales_2024: product_id, quantity_sold

You want to create a combined list of all sales including duplicates for analysis. Which query correctly uses UNION ALL and also adds a column year to identify the source year?
ASELECT product_id, quantity_sold, 'year' FROM Sales_2023 UNION ALL SELECT product_id, quantity_sold, 'year' FROM Sales_2024;
BSELECT product_id, quantity_sold FROM Sales_2023 UNION ALL SELECT product_id, quantity_sold, '2024' AS year FROM Sales_2024;
CSELECT product_id, quantity_sold, year FROM Sales_2023 UNION ALL SELECT product_id, quantity_sold, year FROM Sales_2024;
DSELECT product_id, quantity_sold, '2023' AS year FROM Sales_2023 UNION ALL SELECT product_id, quantity_sold, '2024' AS year FROM Sales_2024;
Step-by-Step Solution
Solution:
  1. Step 1: Add year column with literal values

    Use '2023' and '2024' as string literals to add a year column in each SELECT.
  2. Step 2: Ensure both SELECTs have same columns

    Both SELECTs must have product_id, quantity_sold, and year columns for UNION ALL.
  3. Step 3: Combine with UNION ALL

    SELECT product_id, quantity_sold, '2023' AS year FROM Sales_2023 UNION ALL SELECT product_id, quantity_sold, '2024' AS year FROM Sales_2024; correctly combines both tables with year column and keeps duplicates.
  4. Final Answer:

    SELECT product_id, quantity_sold, '2023' AS year FROM Sales_2023 UNION ALL SELECT product_id, quantity_sold, '2024' AS year FROM Sales_2024; -> Option D
  5. Quick Check:

    Matching columns with year literals + UNION ALL = D [OK]
Quick Trick: Add year as literal in both SELECTs for UNION ALL [OK]
Common Mistakes:
MISTAKES
  • Mismatched columns count in SELECTs
  • Using column name 'year' without value
  • Forgetting to alias literals as year

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More SQL Quizzes