Set operations: does the UNION clause combine the outputs of multiple queries into a single result set?
-
ACorrect
-
BIncorrect
-
COnly if columns are named the same
-
DOnly with UNION ALL
-
EOnly if ORDER BY is present
Answer
Correct Answer: Correct
Explanation
Introduction / Context: UNION is one of SQL’s set operations (UNION, UNION ALL, INTERSECT, EXCEPT/MINUS). It vertically concatenates the results of multiple SELECT statements into a single result set. This question asks if that description is accurate.
Given Data / Assumptions:
- Each SELECT in a UNION must have the same number of columns and union-compatible types.
- UNION removes duplicates; UNION ALL keeps all rows.
- Column names are taken from the first SELECT unless aliased.
Concept / Approach: Conceptually, UNION stacks result sets. After stacking, UNION applies a duplicate elimination step, while UNION ALL does not. Ordering is optional and, when used, applies to the final combined set via a trailing ORDER BY clause.
Step-by-Step Solution:
Prepare two SELECT statements with aligned columns.Combine using SELECT ... UNION SELECT ...Observe the combined rows in one result set.Add ORDER BY at the end if a specific ordering is desired.Verification / Alternative check: Compare UNION vs UNION ALL on datasets with duplicates to see the effect on row counts.
Why Other Options Are Wrong:
- Incorrect: Misrepresents UNION’s role.
- Requiring identical column names / ORDER BY / UNION ALL is unnecessary; structural compatibility is what matters.
Common Pitfalls: Mismatched column counts; forgetting that ORDER BY must reference the combined output; assuming UNION preserves internal ordering of each branch.
Final Answer: Correct