Back to JOINS, UNION, NULL HANDLING

UNION AND UNION ALL

Understand how to combine data from 2 queries using UNION and UNION ALL

7 minutesVideo LessonPDF notes
🎯 Free Guest Mode: You are learning for free. Sign in to save your completion progress and quiz answers.

Ready to continue?

Mark this lesson as complete when you're ready to proceed.

Key moments

  1. UNION Operator — The `UNION` operator combines result sets vertically and automatically removes duplicate rows.
  2. UNION vs DISTINCT — Standard `UNION` behaves identically to `UNION DISTINCT` by default, enforcing uniqueness.
  3. UNION ALL — `UNION ALL` combines result sets without performing duplicate removal, resulting in faster execution.
  4. Labeling Source Rows — Static values can be added as columns to identify which source query contributed a specific row.
  5. Ordering Combined Results — The `ORDER BY` clause must be placed at the end of the entire combined statement to sort the final output.
PDF notes

Frequently asked questions

Does `UNION` combine columns or rows?

`UNION` combines rows (stacks them vertically), unlike `JOIN` which combines columns (horizontally).

Why is `UNION ALL` generally preferred over `UNION`?

`UNION ALL` is significantly faster because it skips the resource-intensive step of checking for and removing duplicate rows.

Can I use `WHERE` clauses with `UNION`?

Yes, you can apply `WHERE` clauses to filter data within each individual `SELECT` statement before the results are combined.

How was this lesson?

Your feedback helps us refine explanations and catch bugs.