Free tutorials & notes in Hindi & English · Clean code examples · Mobile friendly learning
MySQL + SQL · Lesson 76

UNION and UNION ALL in MySQL

UNION Combines Rows; JOIN Combines Columns

UNION is a set operation that stacks compatible query results vertically. JOIN relates tables horizontally and can return columns from both sides in the same row.

OperationCore action
UNIONAppend branches, then remove duplicate result rows
UNION ALLAppend every branch row
JOINMatch related rows using a predicate
Decision: Use UNION ALL when each occurrence matters; use UNION when the required result is a distinct set.

Verified Club Dataset

CREATE TABLE club_a (
  student_name VARCHAR(60) PRIMARY KEY
);
CREATE TABLE club_b (
  student_name VARCHAR(60) PRIMARY KEY
);

INSERT INTO club_a VALUES
('Aarav'), ('Meera'), ('Sana');

INSERT INTO club_b VALUES
('Aarav'), ('Kabir'), ('Sana');

Each club has three members. Aarav and Sana occur in both query results. Across both branches there are six occurrences but only four distinct names.

UNION Removes Duplicate Result Rows

SELECT student_name FROM club_a
UNION
SELECT student_name FROM club_b
ORDER BY student_name;
Aarav Kabir Meera Sana

Duplicate elimination examines the projected result row. If another column such as source label differs, the rows are not duplicates even when student_name is the same.

UNION ALL Preserves All Occurrences

SELECT student_name FROM club_a
UNION ALL
SELECT student_name FROM club_b
ORDER BY student_name;
Aarav Aarav Kabir Meera Sana Sana

Six input occurrences produce six output rows. This is correct for attendance events, transactions or source-preserving pipelines where repeated values represent separate facts.

Column Count, Position and Type Rules

SELECT student_name AS person, 'Club A' AS source
FROM club_a
UNION ALL
SELECT student_name, 'Club B'
FROM club_b;

Both branches return two columns. Corresponding positions must be type-compatible; names come from the first branch, so the final columns are person and source. Do not rely on implicit numeric-to-text conversions when an explicit CAST makes the intended result type clear.

UNION matches columns by position, not by alias. Reversing two same-type columns can produce syntactically valid but semantically wrong data.

Global ORDER BY and Branch LIMIT

SELECT student_name FROM club_a
UNION ALL
SELECT student_name FROM club_b
ORDER BY student_name;

The final ORDER BY applies to all six rows. When a branch must select its own top rows, parenthesize that query block:

(SELECT student_name
 FROM club_a
 ORDER BY student_name
 LIMIT 2)
UNION ALL
(SELECT student_name
 FROM club_b
 ORDER BY student_name
 LIMIT 2)
ORDER BY student_name;
Aarav Aarav Kabir Meera

Without final ORDER BY, display order is not guaranteed even if an individual branch has an access order.

Preserve Source and Count Memberships

SELECT student_name, 'A' AS club_code
FROM club_a
UNION ALL
SELECT student_name, 'B'
FROM club_b
ORDER BY student_name, club_code;
Aarav | A Aarav | B Kabir | B Meera | A Sana | A Sana | B

To count club memberships, wrap this result in a derived table and GROUP BY student_name. Aarav and Sana count 2; Kabir and Meera count 1.

Performance, Mistakes and Practice

  • Choose duplicate semantics before choosing syntax.
  • Project only required columns; wider rows make distinct processing heavier.
  • Filter inside each branch when logically safe.
  • Use compatible collations and data types.
  • Apply final ORDER BY once and use EXPLAIN for representative queries.

Practice: return a distinct four-name roster; retain six membership events; add source labels and explain why UNION no longer collapses shared names; calculate member counts from UNION ALL.

Official References

Syntax and behavior were checked against the official MySQL 8.4 manual. Test every query on a disposable copy before production use.

Frequently Asked Questions

What is the difference between UNION and UNION ALL?
UNION applies duplicate elimination to the combined result. UNION ALL appends every branch row, including duplicates.
How many columns must UNION branches return?
Every query block must return the same number of columns in corresponding positions, with compatible result types.
Where do final column names come from?
The first query block determines the output column names, so give it clear aliases.
Where should ORDER BY be placed?
A final ORDER BY sorts the entire set result. Branch-specific ordering or limiting requires carefully parenthesized query expressions.
Is UNION ALL usually faster?
It avoids global duplicate elimination and is often less work, but choose it because duplicates are valid, then measure the actual plan.
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.