Bird
0
0

You want to combine two queries using UNION ALL but also want to add a column indicating the source table. Which query correctly achieves this?

hard📝 Application Q9 of 15
SQL - Set Operations
You want to combine two queries using UNION ALL but also want to add a column indicating the source table. Which query correctly achieves this?
ASELECT id, 'Table1' AS source FROM table1 UNION ALL SELECT id, 'Table2' AS source FROM table2;
BSELECT id FROM table1 UNION ALL SELECT id, 'Table2' FROM table2;
CSELECT id, source FROM table1 UNION ALL SELECT id, source FROM table2;
DSELECT id, 'Table1' FROM table1 UNION SELECT id, 'Table2' FROM table2;
Step-by-Step Solution
Solution:
  1. Step 1: Add a source column in each SELECT

    SELECT id, 'Table1' AS source FROM table1 UNION ALL SELECT id, 'Table2' AS source FROM table2; adds a literal string column named source in both queries.
  2. Step 2: Use UNION ALL to combine including duplicates

    SELECT id, 'Table1' AS source FROM table1 UNION ALL SELECT id, 'Table2' AS source FROM table2; uses UNION ALL correctly with matching columns.
  3. Step 3: Check other options for errors

    A assumes source column exists in tables, B mismatches columns, D uses UNION (removes duplicates).
  4. Final Answer:

    SELECT id, 'Table1' AS source FROM table1 UNION ALL SELECT id, 'Table2' AS source FROM table2; -> Option A
  5. Quick Check:

    Adding source column with UNION ALL = SELECT id, 'Table1' AS source FROM table1 UNION ALL SELECT id, 'Table2' AS source FROM table2; [OK]
Quick Trick: Add literal column in each SELECT to identify source [OK]
Common Mistakes:
MISTAKES
  • Mismatching column counts
  • Using UNION instead of UNION ALL
  • Assuming source column exists in tables

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More SQL Quizzes