SQL – UNION
Stack results from two SELECT queries vertically using UNION, automatically removing duplicate rows.
Table of Contents
UNION stacks the results of two SELECT statements on top of each other, as if you placed one table directly below another. Unlike a join (which adds columns horizontally), UNION adds rows vertically. Crucially, UNION automatically removes duplicate rows — if the same row appears in both queries, only one copy makes it into the output.
For UNION to work, both SELECT statements must have the same number of columns and compatible data types in corresponding positions.
UNION rules
- Both SELECTs must have the same column count
- Corresponding columns must have compatible types
- Column names come from the FIRST SELECT
- Duplicates are removed automatically
- Use UNION ALL to keep duplicates
Try It Yourself — Interactive SQL Editor
Edit the query below and click Run Query ▶ to see live results powered by SQLite running directly in your browser.
Key Points
- UNION combines rows from two SELECT queries vertically
- Duplicates are automatically removed (use UNION ALL to keep them)
- Column count and types must match across both SELECTs
- The final ORDER BY applies to the entire combined result
Pro Tip from CodesCompiler: The best way to learn SQL is to break things intentionally — modify the query above, change the WHERE conditions, try different columns. Every error teaches you something the docs cannot.
In the next lesson, we continue exploring SQL’s powerful feature set to build your database mastery.