Back to JOINS, UNION, NULL HANDLING

UNION AND UNION ALL

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

8 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 vs JoinUNION combines rows vertically from multiple queries, unlike JOIN which combines columns horizontally.
  2. Basic Union SyntaxThe basic syntax involves placing the UNION keyword between two complete SELECT statements.
  3. Data Consistency RuleAll SELECT statements must select the same number and type of columns for the union to produce meaningful results.
  4. UNION is DISTINCTBy default, UNION acts as UNION DISTINCT, removing duplicate rows from the final combined result set.
  5. Using UNION ALLUNION ALL must be used explicitly if the goal is to include all rows from all queries, including duplicates.
  6. Adding a Label ColumnA constant string column can be added to each SELECT statement to categorize the rows based on the filter criteria applied.
  7. Complex Union Use CaseMultiple SELECT statements can be combined using sequential UNIONs to identify employees meeting various criteria, such as age or salary.
  8. Ordering the Final ResultA single ORDER BY clause placed at the end of the entire union query is used to sort the final combined output.
PDF notes

Frequently asked questions

Which SELECT statement determines the final column names?

The column names and aliases from the very first SELECT statement are used for the final result set.

Can I use WHERE clauses in the individual SELECT statements?

Yes, WHERE clauses are essential for filtering the data subset returned by each individual query before the union occurs.

Can I union results from tables that have no relationship?

Yes, unlike JOINs, UNIONs only require that the selected columns are structurally compatible (same count and data types).

Why did my result set suddenly shrink when I switched from UNION ALL to UNION?

UNION automatically removes duplicate rows that exist across the combined result sets, resulting in fewer total rows.