SQL & Databases Masterclass Course
Welcome to the ultimate postgresql tutorial for beginners 2026. Work through interactive sql practice problems with solutions, master our comprehensive sql window functions tutorial modules, and prepare for tough sql interview questions at Google and Amazon entirely in your browser. Claim your course completion XP and build production-ready database mastery today!
SQL Lesson 20: Combining Datasets with UNION
Introduction & Core Concept
While JOIN operations connect tables horizontally by matching relational keys, database reporting frequently requires combining results from multiple independent queries vertically into a single unified list.
To stack datasets vertically, SQL provides the UNION and UNION ALL set operators.
SELECT name FROM hr_employees
UNION ALL
SELECT name FROM finance_employees;Strict Set Operator Rules
1. Column Count Match: Every SELECT query in the union statement must project the exact same number of columns.
2. Datatype Compatibility: Columns must share compatible datatypes in the exact same index order.
3. Header Naming: The final returned dataset derives its column headers entirely from the aliases defined in the *first* query.
UNION vs. UNION ALL (Performance Critical)
UNION (Implicit De-duplication): Merges rows and performs a CPU-intensive sort across the entire combined dataset to remove duplicate rows.UNION ALL (High-Speed Concatenation): Appends rows directly without sorting or de-duplication checks. It is incredibly fast and efficient!Why & Where We Use It
Real-World Example
StaffCorp needs a consolidated master roster combining employee names and salaries from both their Scranton and Kathmandu branch locations into a single unified report.
Best Practices: What to Do & What NOT to Do
UNION ALL in production code unless you have an explicit business requirement to eliminate duplicates.ORDER BY clauses inside individual sub-queries of a union statement. ORDER BY can only appear once at the very end of the entire unioned query!Syntax & Pro Tips
SELECT name, city FROM employees_east UNION ALL SELECT name, city FROM employees_west;