Ad space (banner)
🗄️SQL Lessons
Lesson 19 / 50

Combining Results with UNION

This lesson covers combining multiple query results with UNION, so information from separate tables can be treated as one result. It's for anyone searching "SQL UNION tutorial."

UNION stacks the results of two SELECT statements vertically into one table, and the two need matching column counts and types. Use UNION ALL if you want to keep duplicate rows.

The example builds an extra "role" column for both a students and a teachers table, then stacks the two with UNION. Notice the distinction: JOIN adds columns "sideways," while UNION adds rows "downward."

A common early mistake is having mismatched column counts or types between the two SELECTs — column names can differ, but the count and order of types must line up, or the query fails. This is the tool for "merge students and teachers into a single contact list" — two tables that were separate becoming one result — and it automatically removes exact duplicate rows along the way, so no manual dedup step is needed.

SQL
OUTPUT

💡 The SQL engine may take a few seconds to load the first time you run code.

Ad space (banner)
Ad space (in-article)