ποΈ SQL Β· Topic 14 of 20
Set Operations β SQL Questions with Answers
30 practice questions on Set Operations, each with the correct answer and a clear explanation of why it is right. Read through them as revision notes, or take this topic as an interactive quiz to test yourself.
2 easy Β· 15 medium Β· 13 hard Β· Part of SQL: Databases from basics to window functions - 20 topics.
Medium questions (15)
Q3. medium
What must be true for two queries to be combined with UNION?
- A They must have the SAME number of columns, in compatible data types and order
- B They must query the same table
- C They must have the same column names
- D Nothing
Answer: A β They must have the SAME number of columns, in compatible data types and order
UNION aligns columns by POSITION, not name. Column 1 of both queries must be type-compatible, and so on. The result uses the first query's column names.
UNIONCompatibility
Q5. medium
What does INTERSECT return?
SELECT email FROM customers
INTERSECT
SELECT email FROM newsletter_subscribers;
- A Only rows that appear in BOTH queries
- B All rows from both
- C Rows in the first but not the second
- D Nothing
Answer: A β Only rows that appear in BOTH queries
INTERSECT is the overlap - customers who are also suppliers, for example. Like UNION, it removes duplicates by default.
INTERSECTOverlap
Q6. medium
What does EXCEPT (or MINUS in Oracle) return?
SELECT email FROM customers
EXCEPT
SELECT email FROM unsubscribed;
- A Rows in the FIRST query that are NOT in the second
- B Rows in both
- C All rows
- D Rows in the second only
Answer: A β Rows in the FIRST query that are NOT in the second
EXCEPT is set difference. Customers who never subscribed = customers EXCEPT subscribers. Oracle spells it MINUS; the meaning is identical.
EXCEPTMINUSSet difference
Q8. medium
How does UNION handle the column NAMES of the result?
- A It uses the column names (or aliases) from the FIRST SELECT
- B It combines both names
- C It uses the second query's names
- D Columns become unnamed
Answer: A β It uses the column names (or aliases) from the FIRST SELECT
Only the first query's names (or aliases) appear in the output. Alias the first query's columns to control the result headers.
UNIONColumn names
Q10. medium
How do you tag which query each row came from in a UNION?
- A Add a literal column: SELECT name, 'A' AS source ... UNION ALL SELECT name, 'B' ...
- B It is automatic
- C Use GROUP BY
- D It cannot be done
Answer: A β Add a literal column: SELECT name, 'A' AS source ... UNION ALL SELECT name, 'B' ...
A constant column labels the origin of each row - very useful when merging similar data from different sources into one list.
UNIONLiterals
Q12. medium
Can you UNION more than two queries?
- A Yes - chain them: SELECT ... UNION SELECT ... UNION SELECT ...
- B No, only two
- C Only with ALL
- D Only three
Answer: A β Yes - chain them: SELECT ... UNION SELECT ... UNION SELECT ...
Any number of compatible queries can be unioned. Each must have the same column count and compatible types.
UNIONChaining
Q14. medium
What happens if the two queries have different column COUNTS?
- A An error - 'each UNION query must have the same number of columns'
- B Missing columns become NULL
- C Extra columns are dropped
- D It works anyway
Answer: A β An error - 'each UNION query must have the same number of columns'
The counts must match exactly. If one query lacks a column, add a placeholder like NULL AS missing_col or a constant to line them up.
UNIONErrors
Q16. medium
Does INTERSECT remove duplicates?
- A Yes - like UNION, it returns distinct rows (INTERSECT ALL keeps duplicates where supported)
- B No, it keeps all
- C Only for text
- D It errors on duplicates
Answer: A β Yes - like UNION, it returns distinct rows (INTERSECT ALL keeps duplicates where supported)
The set operators default to distinct results. Some databases offer INTERSECT ALL and EXCEPT ALL to preserve duplicate multiplicities.
INTERSECTDuplicates
Q18. medium
What is a practical use of UNION ALL with literals?
SELECT * FROM (VALUES ('S'),('M'),('L')) AS sizes(label);
- A Building a small fixed list of values inline without creating a table
- B Deleting rows
- C Indexing
- D Sorting
Answer: A β Building a small fixed list of values inline without creating a table
SELECT 'S' UNION ALL SELECT 'M' UNION ALL SELECT 'L' creates a quick lookup set. (Modern SQL also offers VALUES lists for this.)
UNION ALLVALUES
Q20. medium
How do you combine two monthly report queries into one result?
- A UNION ALL the two SELECTs (rows are distinct by month, so no dedup needed)
- B JOIN them
- C INTERSECT them
- D CROSS JOIN them
Answer: A β UNION ALL the two SELECTs (rows are distinct by month, so no dedup needed)
When each query returns non-overlapping rows, UNION ALL simply stacks them efficiently. Add a month label column to distinguish the segments.
UNION ALLReporting
Q22. medium
Can you apply LIMIT to a UNION result?
- A Yes - a LIMIT (with ORDER BY) at the end applies to the combined result
- B No, LIMIT is forbidden
- C Only in each SELECT
- D Only with INTERSECT
Answer: A β Yes - a LIMIT (with ORDER BY) at the end applies to the combined result
Place ORDER BY and LIMIT after the final query to page the whole union. To limit an individual branch, wrap that SELECT in a subquery.
UNIONLIMIT
Q24. medium
Do the queries in a UNION need matching WHERE clauses?
- A No - each SELECT can have completely different logic, as long as the output columns line up
- B Yes, identical WHERE
- C They must query one table
- D WHERE is not allowed
Answer: A β No - each SELECT can have completely different logic, as long as the output columns line up
The branches are independent queries; only their output shape must match. This flexibility lets you merge quite different selections into one list.
UNIONFlexibility
Q26. medium
How do you deduplicate a combined list of tags from two tables?
- A SELECT tag FROM a UNION SELECT tag FROM b (UNION removes duplicates)
- B UNION ALL
- C JOIN a and b
- D CROSS JOIN
Answer: A β SELECT tag FROM a UNION SELECT tag FROM b (UNION removes duplicates)
Plain UNION is exactly the tool for a distinct merged list. Use UNION ALL only if you deliberately want to keep the repeats.
UNIONDeduplication
Q28. medium
Which set operation answers 'who is in both group A and group B'?
- A INTERSECT
- B UNION
- C EXCEPT
- D CROSS JOIN
Answer: A β INTERSECT
INTERSECT returns the common membership. UNION would give everyone in either group, and EXCEPT gives those in one but not the other.
INTERSECTMembership
Q30. medium
Which set operation combines two result sets and keeps duplicates for maximum speed?
- A UNION ALL
- B UNION
- C INTERSECT
- D EXCEPT
Answer: A β UNION ALL
UNION ALL simply appends the second result to the first with no de-duplication pass, so it is the fastest way to stack rows. Use plain UNION only when you actually need to remove duplicates.
UNION ALLPerformance
Hard questions (13)
Q4. hard
Where does ORDER BY go in a UNION query?
SELECT name, 'customer' AS type FROM customers
UNION ALL
SELECT name, 'supplier' FROM suppliers
ORDER BY name;
- A At the very END, after the last SELECT - it sorts the combined result
- B In each SELECT
- C Before UNION
- D ORDER BY is not allowed
Answer: A β At the very END, after the last SELECT - it sorts the combined result
A single ORDER BY at the end applies to the whole union. Putting it inside an individual SELECT is either an error or ignored, since the union reorders everything anyway.
UNIONORDER BY
Q7. hard
Is EXCEPT symmetric - does A EXCEPT B equal B EXCEPT A?
- A No - order matters; A EXCEPT B keeps A's extras, B EXCEPT A keeps B's extras
- B Yes, always symmetric
- C Only for numbers
- D They both return everything
Answer: A β No - order matters; A EXCEPT B keeps A's extras, B EXCEPT A keeps B's extras
Set difference is directional, unlike UNION and INTERSECT which are symmetric. Choose the order based on which side's unmatched rows you want.
EXCEPTDirection
Q9. hard
Why might UNION ALL be preferred even when duplicates are possible?
- A It avoids the costly de-duplication sort; if downstream logic handles duplicates, it is faster
- B It is always wrong
- C It removes more duplicates
- D It sorts automatically
Answer: A β It avoids the costly de-duplication sort; if downstream logic handles duplicates, it is faster
On large data the distinct pass of UNION is expensive. When you know rows are unique (e.g. non-overlapping date ranges), UNION ALL gives the same result faster.
UNION ALLPerformance
Q11. hard
What is the precedence between INTERSECT and UNION when combined?
- A INTERSECT binds tighter than UNION/EXCEPT - use parentheses to be explicit
- B UNION binds tighter
- C They are equal, left to right
- D You cannot combine them
Answer: A β INTERSECT binds tighter than UNION/EXCEPT - use parentheses to be explicit
In standard SQL INTERSECT has higher precedence, so A UNION B INTERSECT C means A UNION (B INTERSECT C). Parentheses remove any doubt and improve readability.
PrecedenceSet operations
Q13. hard
When would you use UNION instead of a JOIN?
- A When STACKING similar rows from different sources (adding rows), not correlating tables (adding columns)
- B They are interchangeable
- C UNION is always better
- D Never use UNION
Answer: A β When STACKING similar rows from different sources (adding rows), not correlating tables (adding columns)
JOIN answers 'what related data goes with this row?'. UNION answers 'combine these two lists into one'. Choosing the right one starts with whether you need more columns or more rows.
UNION vs JOIN
Q15. hard
How do you find values in table A that are NOT in table B, using set operations?
- A SELECT x FROM A EXCEPT SELECT x FROM B
- B A INTERSECT B
- C A UNION B
- D A JOIN B
Answer: A β SELECT x FROM A EXCEPT SELECT x FROM B
EXCEPT is the direct set-difference tool. Alternatives include LEFT JOIN ... IS NULL and NOT EXISTS, which can be faster and handle multiple columns more flexibly.
EXCEPTAnti-join
Q17. hard
How do set operations treat NULLs when deciding if rows are equal?
- A They treat two NULLs as the SAME (unlike = comparisons), so duplicate NULL rows collapse
- B NULLs are always different
- C NULLs are removed
- D It errors
Answer: A β They treat two NULLs as the SAME (unlike = comparisons), so duplicate NULL rows collapse
Set operations use 'not distinct' semantics: NULL matches NULL for de-duplication and intersection. This differs from the WHERE clause, where NULL = NULL is UNKNOWN.
NULLSet operations
Q19. hard
Why does data-type compatibility matter in UNION?
- A Corresponding columns are merged, so mixing e.g. a number and a date causes an error or implicit conversion
- B It does not matter
- C Types are ignored
- D Only names matter
Answer: A β Corresponding columns are merged, so mixing e.g. a number and a date causes an error or implicit conversion
Each output column takes a single type derived from both inputs. Incompatible types (text vs date) either fail or coerce unexpectedly - align them with CAST.
Type compatibilityCAST
Q21. hard
What is the row count of 'SELECT 1 UNION SELECT 1 UNION ALL SELECT 1'?
- A 2 - the first UNION dedups to one, then UNION ALL adds another
- B 3
- C 1
- D An error
Answer: A β 2 - the first UNION dedups to one, then UNION ALL adds another
Evaluated left to right: SELECT 1 UNION SELECT 1 gives one row, then UNION ALL SELECT 1 appends a duplicate, giving two. Mixing UNION and UNION ALL requires care.
UNIONUNION ALL
Q23. hard
How would you find emails common to two lists AND unique to the first, in one query set?
- A Use INTERSECT for the common ones and EXCEPT for the unique ones (as separate queries or combined with care)
- B One UNION does it
- C A single JOIN
- D It is impossible
Answer: A β Use INTERSECT for the common ones and EXCEPT for the unique ones (as separate queries or combined with care)
INTERSECT gives the overlap; EXCEPT gives list-one-only. Set operators are a clean vocabulary for these membership questions, complementing joins.
INTERSECTEXCEPT
Q25. hard
What is a performance advantage of EXCEPT/INTERSECT over equivalent joins?
- A They express set logic concisely and can be optimised well - though NOT EXISTS/LEFT JOIN are sometimes faster on large indexed data
- B They are always fastest
- C They never use indexes
- D There is no difference ever
Answer: A β They express set logic concisely and can be optimised well - though NOT EXISTS/LEFT JOIN are sometimes faster on large indexed data
Set operators are readable for whole-row membership tests. For large tables, benchmark against NOT EXISTS and anti-joins, which can leverage indexes more directly.
PerformanceEXCEPT
Q27. hard
Why must you sometimes wrap a UNION in a subquery?
- A To apply further operations (GROUP BY, JOIN, additional filtering) to the combined result as a whole
- B UNION cannot be used otherwise
- C For syntax reasons only
- D You never need to
Answer: A β To apply further operations (GROUP BY, JOIN, additional filtering) to the combined result as a whole
A UNION is a single result set; to aggregate or join it, place it in a subquery or CTE: SELECT type, COUNT(*) FROM (SELECT ... UNION ALL ...) t GROUP BY type.
SubqueriesUNION
Q29. hard
What is the safest way to ensure UNION columns align correctly?
- A Explicitly list and, if needed, CAST each column in both queries in the same order
- B Use SELECT * in both
- C Rely on column names matching
- D Add extra columns
Answer: A β Explicitly list and, if needed, CAST each column in both queries in the same order
SELECT * across differently structured tables is fragile - column order or count can drift. Naming (and casting) columns makes the alignment explicit and change-proof.
UNIONBest practices