Combining SQL Results with UNION and UNION ALL
UNION ALL preserves rows from both inputs, including repeats. UNION removes duplicate combined result rows.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Trace two small inputs
Results (A,B) and (B,C), each a sequence of one-column records, produce four rows under UNION ALL. UNION produces three distinct values. See set and sequence models.
Choose based on provenance
If a repeated label identifies separate observations, include IDs or keep duplicates deliberately. An explicit final order rule is needed if row ordering matters after combining.[1]
Show how equal rows lose multiplicity
Two data sources contribute labels A, B and B, C. UNION ALL returns four rows including both occurrences of B. UNION returns the set of three projected labels. If source history matters, add a source attribute or retain repeated events. See sets versus sequences.
Source one: A,B
Source two: B,C
UNION ALL count: 4
UNION count: 3
Specify a final order independently
A set operation does not promise that one source's rows appear first. Apply a final ordering if the caller needs it. Test a duplicate within one input and across both.