This lesson on UNION AND UNION ALL is hands-on and example-driven. You will learn how to combine the rows returned by multiple independent SELECT statements into a single result set using the UNION operator. You will be able to differentiate between combining only unique rows (UNION) and combining all rows (UNION ALL). This technique is essential for merging data subsets that meet different criteria into one cohesive report.
What You'll Be Able To Do
- Combine rows from separate queries using the UNION operator.
- Differentiate between UNION (distinct) and UNION ALL (all rows).
- Ensure column count and data types are consistent across unioned queries.
- Apply filtering criteria (e.g., WHERE clauses) to individual SELECT statements within a union.
- Use unions to categorize and label rows based on different selection criteria.
- Apply ORDER BY only once to the final combined result set.
Topics Covered in UNION AND UNION ALL
- Union vs Join (0:00 - 0:30) — UNION combines rows vertically from multiple queries, unlike JOIN which combines columns horizontally.
- Basic Union Syntax (0:30 - 1:30) — The basic syntax involves placing the UNION keyword between two complete SELECT statements.
- Data Consistency Rule (1:30 - 3:00) — All SELECT statements must select the same number and type of columns for the union to produce meaningful results.
- UNION is DISTINCT (3:00 - 4:30) — By default, UNION acts as UNION DISTINCT, removing duplicate rows from the final combined result set.
- Using UNION ALL (4:30 - 5:30) — UNION ALL must be used explicitly if the goal is to include all rows from all queries, including duplicates.
- Adding a Label Column (5:30 - 7:30) — A constant string column can be added to each SELECT statement to categorize the rows based on the filter criteria applied.
- Complex Union Use Case (7:30 - 10:00) — Multiple SELECT statements can be combined using sequential UNIONs to identify employees meeting various criteria, such as age or salary.
- Ordering the Final Result (10:00 - 11:30) — A single ORDER BY clause placed at the end of the entire union query is used to sort the final combined output.
SQL Cheat Sheet
-
SELECT <cols> FROM <table> UNION SELECT <cols> FROM <table>;— Combines results of two SELECT statements, automatically removing duplicatesSELECT first_name, last_name FROM employee_demographics UNION SELECT first_name, last_name FROM employee_salary; -
UNION ALL— Combines results of two SELECT statements, retaining all rows, including duplicatesSELECT first_name, last_name FROM employee_demographics UNION ALL SELECT first_name, last_name FROM employee_salary; -
Data Consistency Rule— All SELECT statements must return the same number and type of columnsSELECT first_name, last_name FROM employee_demographics UNION SELECT first_name, last_name FROM employee_salary; -
Labeling Column— Adds a constant string column to identify the source or category of the rowSELECT first_name, last_name, 'Old Man' AS label FROM employee_demographics WHERE age > 50; -
Multiple Unions— Allows combining results from three or more SELECT statements sequentiallySELECT first_name FROM T1 UNION SELECT first_name FROM T2 UNION SELECT first_name FROM T3; -
ORDER BY— Sorts the entire combined result set based on specified columnsSELECT first_name, last_name FROM T1 UNION ALL SELECT first_name, last_name FROM T2 ORDER BY first_name;
Comparison Table
| Comparison | UNION (Default) | UNION ALL |
|---|---|---|
| Duplicate Handling | Removes duplicates (DISTINCT) | Keeps all rows |
| Speed | Slower (Requires sorting) | Faster (Simple concatenation) |
| Use Case | Unique list of values | Full data audit |
| Keyword Required | No (Default behavior) | Yes (Must be specified) |
Common Pitfalls
- Mistake: Selecting different numbers or types of columns in each query. Avoid: Ensure all SELECT statements return identical column structure.
- Mistake: Expecting all rows to appear when using the default UNION operator. Avoid: Use UNION ALL explicitly if duplicates must be included in the output.
- Mistake: Applying ORDER BY to the first SELECT statement only. Avoid: Place the single ORDER BY clause at the very end of the entire union query.
- Mistake: Mixing data types that represent different concepts (e.g., age and name). Avoid: Keep the meaning of corresponding columns consistent across all queries.
FAQs
- 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.