smartyfy.mrindigi.com

Databases & SQL Master Course — 046. UNION and UNION ALL

Lesson 046 UNION and UNION ALL

Two sources can describe the same kind of records without being related row by row. UNION combines their result sets vertically. UNION ALL keeps every input result row; UNION removes duplicate output rows. Choosing between them requires knowing whether repeated values represent repeated events or repeated representations of the same requested category.

Prerequisites and objectives

Complete Lesson 045. You should understand SELECT, DISTINCT, aliases, ordering, and result grain. You will combine compatible column lists, preserve source identity, predict duplicate removal, and avoid losing legitimate repeated events through an unjustified UNION.

Step 1 Define the source records

Run this setup once in a fresh empty SQLite practice database. Each table records fictional workshop signups from a different intake channel. IDs are unique within a table, not globally across both channels. seats records the number of seats requested by that signup.

CREATE TABLE web_signups (signup_id INTEGER PRIMARY KEY, city TEXT, seats INTEGER);
CREATE TABLE desk_signups (signup_id INTEGER PRIMARY KEY, city TEXT, seats INTEGER);
INSERT INTO web_signups VALUES (1,'North',2),(2,'South',1),(3,'North',2);
INSERT INTO desk_signups VALUES (1,'North',2),(2,'West',3);

There are three Web signups and two Desk signups. Several records share city North and seats 2, but that does not prove they are the same signup. A result containing only city and seats has discarded the source identifiers that distinguish the occurrences.

Step 2 Preserve occurrences with UNION ALL

Both component SELECTs must return the same number of columns in corresponding positions. The values should also have compatible meanings and units.

SELECT city, seats FROM web_signups
UNION ALL
SELECT city, seats FROM desk_signups
ORDER BY city, seats;

Five rows remain, including three North-and-two combinations. UNION ALL does not pair Web rows with Desk rows; that would be a join-style operation. It appends compatible result rows into one combined result, preserving their multiplicity.

Step 3 Understand duplicate elimination

Changing UNION ALL to UNION removes repeated complete output rows.

SELECT city, seats FROM web_signups
UNION
SELECT city, seats FROM desk_signups
ORDER BY city, seats;

The result now has three combinations. This can be correct if the question asks which city-and-seat combinations occurred. It is incorrect if the question asks for every signup, because three distinct source records have been collapsed into one displayed combination.

Duplicate elimination compares the selected output row, not a hidden business identity. It cannot determine whether two matching rows represent the same real-world registration. Deduplicating actual intake records requires a defined identity and conflict policy, not merely a keyword that produces fewer rows.

Input cards preserve Web IDs 1, 2, 3 with North/2, South/1, North/2 and Desk IDs 1, 2 with North/2, West/3. UNION ALL produces five occurrences, including three North/2 rows, totaling ten requested seats. UNION on city and seats produces three unique combinations whose seat values sum to six, explicitly not a signup total.
Choose whether the question concerns occurrences or distinct selected values before choosing the operator. Equal descriptions do not establish equal event identity. Open full-size diagram

Step 4 Preserve lineage explicitly

Add a source label and the source-local ID when the combined result needs traceable event identity.

SELECT 'Web' AS source, signup_id, city, seats FROM web_signups
UNION ALL
SELECT 'Desk' AS source, signup_id, city, seats FROM desk_signups
ORDER BY source, signup_id;

The pair source and signup_id distinguishes every record. Desk ID 1 and Web ID 1 are not automatically the same event. Keeping lineage makes reconciliation and later investigation possible even when descriptive fields repeat.

Step 5 Align columns by meaning

Compound queries align values by position, not by matching column names. If one SELECT returns city then seats while the other returns seats then city, the output mixes incompatible meanings. SQLite’s flexible typing may allow surprising mixtures, so successful execution alone is a weak compatibility check.

Write explicit column lists in the same semantic order and use clear aliases in the first component. The first SELECT determines the output column names in these examples. If the sources use different representations, normalize them deliberately before combining rather than relying on automatic coercion.

Step 6 Order the combined result

The final ORDER BY applies to the compound result. Do not assume Web records appear before Desk records merely because their SELECT is written first. Without an explicit final order, no presentation sequence is guaranteed.

SQLite has specific restrictions on expressions in a compound query’s ORDER BY. Using selected column names, as these examples do, keeps the intent clear. If a more complicated outer transformation is needed, place the compound result in a derived table or CTE and query that named relation.

Step 7 Reconcile quantities

The source seats total five on Web and five at the Desk, giving ten requested seats. Summing the UNION ALL event stream should preserve ten. Summing the distinct city-and-seat combinations would give six, because two legitimate North occurrences were removed. A correct total depends on retaining the appropriate grain.

UNION also performs duplicate-elimination work, but do not reduce the choice to an unsupported claim that one spelling is always faster in every system. Select the semantics first; measure relevant performance later. Correctly preserving or eliminating records is the primary decision.

Practice with worked solutions

Exercise 1

List each observed city once across both sources.

Worked solution
SELECT city FROM web_signups
UNION
SELECT city FROM desk_signups
ORDER BY city;

North, South, and West form a category list. Here removing repeated city values is intentional because the result grain is one city, not one signup.

Exercise 2

Build a combined event CTE and calculate its row count and seat total.

Worked solution
WITH signups AS (
 SELECT city, seats FROM web_signups
 UNION ALL SELECT city, seats FROM desk_signups
)
SELECT COUNT(*) AS signups, SUM(seats) AS requested_seats FROM signups;

Five signup rows request ten seats. This agrees with the source counts and amounts because UNION ALL preserves every event occurrence.

Exercise 3

Demonstrate the reduced count and amount when UNION is applied to city and seats.

Worked solution
WITH combinations AS (
 SELECT city, seats FROM web_signups
 UNION SELECT city, seats FROM desk_signups
)
SELECT COUNT(*) AS combinations, SUM(seats) AS combination_seats FROM combinations;

Three unique combinations sum to six seats. That measure is not a signup-seat total, so its label must not imply that it reconciles to the ten requested seats.

Exercise 4

Return source and local ID for every North signup.

Worked solution
SELECT 'Web' AS source, signup_id FROM web_signups WHERE city = 'North'
UNION ALL
SELECT 'Desk' AS source, signup_id FROM desk_signups WHERE city = 'North'
ORDER BY source, signup_id;

Three distinct source identities remain visible. Matching descriptive city and seat values did not justify merging these records.

Knowledge check

Question 1

What does UNION ALL preserve?

  1. Every component result row
  2. Only the first source
  3. Only unique city values
  4. Only matching pairs
Answer and explanation

A. It appends rows without duplicate elimination.

Question 2

How are component columns aligned?

  1. By alphabetical order
  2. By primary-key relationships
  3. By similar names
  4. By position
Answer and explanation

D. Corresponding positions must carry compatible meanings.

Question 3

What does UNION remove?

  1. Duplicate complete selected rows
  2. All NULL values
  3. All repeated words
  4. Every repeated source ID globally
Answer and explanation

A. It compares the projected output, not a hidden event identity.

Question 4

Why retain source with a local signup ID?

  1. To collapse identical requests across channels
  2. To deduplicate equal quantities
  3. To distinguish identities from separate ID namespaces
  4. To align columns by their names
Answer and explanation

C. Local IDs can overlap across channels without identifying the same event.

Question 5

What is the correct total requested seat count?

  1. Three
  2. Ten
  3. Six
  4. Five
Answer and explanation

B. All five recorded signup occurrences contribute their requested quantities.

Pitfalls and summary

Do not use UNION as an unexplained data-cleaning shortcut or confuse vertical combination with row matching. Align columns by meaning, preserve lineage when events matter, and apply one final order. Choose duplicate handling from the requested result grain and reconcile its consequences.

SQLite behavior and references

Examples were checked with SQLite 3.53.1 on 10 October 2026. Use a SQLite SQL editor; Python is not a prerequisite. Verify dialect-specific functions, comparison rules, and numeric behavior before moving the examples to another engine.

Primary references