Sub topic 1
Combining result sets: the idea behind set operators
Prerequisites
This chapter assumes you can write basic SELECT queries with WHERE, that you understand tables, rows, and columns, and that you know how DISTINCT and NULL behave. The examples use UNION and UNION ALL, which run on PostgreSQL, MySQL, SQLite, and SQL Server.
The idea behind set operators
A set operator stacks the rows returned by one SELECT on top of the rows returned by another. The operator then decides which rows to keep. Each query's result is treated as a set of rows, so the same rules apply to any pair of queries that return compatible columns.
Making two queries compatible
Both queries must return the same number of columns, in the same order, with data types the database can match. The column names in the final result come from the first query.
SELECT id, name FROM customers
UNION
SELECT id, name FROM suppliers;UNION: merging results and removing duplicates
UNION returns each distinct row once. To remove duplicates, the database must compare the combined rows, which costs extra work.
SELECT email FROM customers
UNION
SELECT email FROM newsletter_subscribers;UNION ALL: keeping every row
UNION ALL keeps every row from both queries, including duplicates. It skips the duplicate check, so it usually runs faster. Use it when the inputs cannot overlap, or when a repeated row is meaningful.
SELECT email, 'customer' AS source FROM customers
UNION ALL
SELECT email, 'subscriber' AS source FROM newsletter_subscribers;Exercise
You combine a list of orders from 2025 with a list of orders from 2026. No order appears in both lists. Which operator should you use, and why?
Show answer
Use UNION ALL. The lists do not overlap, so UNION's duplicate check does no useful work and only adds cost.