SQL UNION combines the result sets of two or more SELECT statements into a single output, removing duplicate rows unless UNION ALL is used. Each query must return the same number of columns with compatible data types, and column order matters.
SQL UNION merges the outputs of two or more SELECT statements into a single result set and removes duplicate rows automatically.
SQL UNION is ideal when you need one consolidated list from tables or queries that share the same logical structure but store related data separately.
Each SELECT produces a temporary table. The database stacks these tables vertically, then applies DISTINCT logic across all columns to discard duplicates.
You must write individual SELECTs with matching column counts, compatible data types, and the same column order, then join them with the UNION keyword.
Use UNION ALL when duplicate rows are meaningful or performance matters, because UNION ALL skips the de-duplication step and returns rows faster.
You can chain as many SELECT statements as needed: SELECT … UNION SELECT … UNION SELECT … . Every added query must follow the same column structure.
The column names from the first SELECT statement become the names of the output columns, regardless of aliases used in later SELECTs.
Place ORDER BY or LIMIT after the final SELECT block to sort or trim the combined set. Each inner query can have its own ORDER BY only if enclosed in parentheses with LIMIT.
Common scenarios include merging archived and live data, unifying region-partitioned tables, or producing a combined list of current and historical records.
UNION stacks rows vertically (adding more rows), while JOIN merges columns horizontally (adding more attributes). Choose UNION when schemas match and you need more rows.
UNION incurs overhead for duplicate removal. Indexes on participating columns and using UNION ALL when possible improve performance.
Explicitly cast mismatched data types, align column lists instead of using SELECT *, and test with UNION ALL first to verify row counts.
Error messages like “columns of query do not match” indicate column count or data-type mismatches. Compare SELECT lists side by side to resolve quickly.
Use parentheses to control precedence when mixing UNION with other set operators (INTERSECT, EXCEPT) or when adding individual ORDER BY clauses.
SQL UNION unifies structurally similar queries, removes duplicates, and simplifies reporting across partitioned or archived tables. Follow column-matching rules and prefer UNION ALL for speed when duplicates are acceptable.
UNION ALL is usually faster because it skips duplicate removal. Choose it when duplicates are acceptable.
Yes. Alias columns in each SELECT so the positions align and data types are compatible.
No. Without an ORDER BY clause, SQL returns rows in an undefined order. Add ORDER BY after the last SELECT to control sorting.
Absolutely. Create a view that contains a UNION to provide a reusable combined dataset.
NONE