SQL / MySQL Intermediate Queries · 8 min read

UNION of Two Result Sets

Lesson 18 of 33 in the SQL / MySQL learning path.

How do I stack two SELECT results in one list?

UNION stacks the rows of two SELECT statements into one result. Each branch must return the same number of columns, in the same order, with types MySQL can combine. The column names in the combined list come from the first SELECT. UNION removes rows that are identical across every column. UNION ALL keeps those duplicates and does less work because it does not have to search for them.

The school examples build two lists. One stacks student names and lesson titles, marked with a kind column so a name and a title stay distinct. The other stacks math titles with published titles so you can see UNION drop the repeated Algebra I row and UNION ALL keep both copies. ORDER BY belongs after the last branch and sorts the combined list.

Syntax & Parameters

Syntax
SELECT name AS label, 'user' AS kind FROM users
UNION
SELECT title, 'lesson' FROM lessons
ORDER BY kind, label;

Example

queries.sql
CREATE DATABASE IF NOT EXISTS school
  CHARACTER SET utf8mb4
  COLLATE utf8mb4_unicode_ci;

USE school;

SET NAMES utf8mb4;

DROP VIEW IF EXISTS roster;
DROP TABLE IF EXISTS enrollments;
DROP TABLE IF EXISTS lessons;
DROP TABLE IF EXISTS users;

CREATE TABLE users (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT,
  name VARCHAR(120) NOT NULL,
  email VARCHAR(254) NOT NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_users_email (email)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE lessons (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT,
  title VARCHAR(160) NOT NULL,
  track VARCHAR(80) NOT NULL,
  published_at DATETIME NULL,
  PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE enrollments (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT,
  lesson_id INT UNSIGNED NOT NULL,
  user_id INT UNSIGNED NOT NULL,
  status VARCHAR(20) NOT NULL,
  PRIMARY KEY (id),
  UNIQUE KEY uq_enrollments_lesson_user (lesson_id, user_id),
  CONSTRAINT fk_enrollments_lesson FOREIGN KEY (lesson_id) REFERENCES lessons (id),
  CONSTRAINT fk_enrollments_user FOREIGN KEY (user_id) REFERENCES users (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT INTO users (name, email, created_at) VALUES
  ('Ada Lovelace', 'ada@school.test', '2026-03-01 09:00:00'),
  ('Grace Hopper', 'grace@school.test', '2026-03-14 11:00:00'),
  ('Alan Turing', 'alan@school.test', '2026-03-18 08:30:00');

INSERT INTO lessons (title, track, published_at) VALUES
  ('Algebra I', 'math', '2026-03-02 09:00:00'),
  ('Geometry', 'math', NULL),
  ('SQL Basics', 'data', '2026-03-10 09:00:00'),
  ('Studio Draft', 'art', NULL);

(SELECT name AS label, 'user' AS kind FROM users)
UNION
(SELECT title, 'lesson' FROM lessons)
ORDER BY kind, label;

(SELECT title AS label
 FROM lessons
 WHERE track = 'math')
UNION
(SELECT title
 FROM lessons
 WHERE published_at IS NOT NULL)
ORDER BY label;

(SELECT title AS label
 FROM lessons
 WHERE track = 'math')
UNION ALL
(SELECT title
 FROM lessons
 WHERE published_at IS NOT NULL)
ORDER BY label;

Expected Output

label        | kind
Algebra I    | lesson
Geometry     | lesson
SQL Basics   | lesson
Studio Draft | lesson
Ada Lovelace | user
Alan Turing  | user
Grace Hopper | user
7 rows in set

label
Algebra I
Geometry
SQL Basics
3 rows in set

label
Algebra I
Algebra I
Geometry
SQL Basics
4 rows in set

Line-by-Line Walkthrough

  1. The script loads three students and four lessons. Algebra I is both math and published. Geometry is math and still a draft. SQL Basics is published and is not math. Studio Draft is neither.
  2. The first query stacks names and titles. Both branches return two columns, a label and a kind.
  3. UNION compares the full row. A student and a lesson stay separate because the kind value differs.
  4. Column names in the output come from the first branch, so the second branch can select title without renaming it.
  5. ORDER BY kind, label sorts the combined list. It is not a sort of each branch on its own.
  6. The second query stacks math titles with published titles and uses UNION, so Algebra I appears once.
  7. Geometry appears only from the math branch. SQL Basics appears only from the published branch. Studio Draft appears in neither.
  8. The third query is the same pair of SELECT statements with UNION ALL, so Algebra I appears twice.
  9. Use UNION ALL when every row from both branches must survive, including duplicates. Use UNION when the list should show each distinct row once.

Common Pitfalls & Security

UNION is a stack of result sets, not a join. It does not match students to lessons. A branch with a different column count is a syntax error, and a branch that hides a duplicate can make a report look shorter than the tables really are.

  • UNION removes a row only when every selected column matches. Add a kind or source column when those rows must stay distinct.
  • ORDER BY inside a branch is discarded unless that branch also has LIMIT. Put the sort after the last branch when the combined list needs an order.
  • UNION ALL is the right tool for a report that must count both copies. Switching to UNION silently drops repeats.
  • The first SELECT fixes the column names and the expected types. A date stacked on a title can coerce and surprise you.
  • A UNION of two broad queries can still leak drafts and emails. Filter each branch, and do not wrap the whole thing around a table the caller should not read.

Best Practices & Modern Standards

Write each branch so it could run alone, with the same columns in the same order. Prefer UNION ALL when you already know the branches cannot overlap, or when duplicates are meaningful. Use UNION when the product requirement is a distinct list. Put a source column in the SELECT list whenever the caller needs to know which branch produced the row.

Keep ORDER BY and LIMIT on the combined result unless you intentionally want the top rows of one branch. Parentheses make that branch-level LIMIT legal in MySQL. Bind any filter values from PHP, and keep the UNION structure in the statement text.

Real-World Use

The office wants one alphabetical picker that contains student names and lesson titles. A UNION stacks the two SELECT results and a kind column tells the form which table the row came from. A second report lists math titles together with published titles and uses UNION so Algebra I, which qualifies for both, shows up once.

Frequently Asked Questions

What does UNION remove that UNION ALL keeps?

UNION removes rows that are identical in every selected column. UNION ALL keeps every row from both branches, so Algebra I appears twice in the third query.

Why must both SELECT statements return the same number of columns?

MySQL stacks columns by position. A branch with a different column count is rejected. Matching types belong in those positions too, so a title stays stacked on a title.

Where do the column names come from?

The first SELECT names the combined columns. The later branches only supply values. label and kind in this lesson come from the users branch.

Where should ORDER BY go?

After the last branch, so it sorts the stacked list. An ORDER BY inside one branch does not sort that branch unless the branch also uses LIMIT.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…