PostgreSQL UNION
Overview
The UNION operator combines the result sets of two or more SELECT statements into a single result set. It removes duplicate rows by default. UNION is useful when you need to combine data from multiple tables or queries with similar structures.
Basic Syntax
UNION vs UNION ALL
UNION (Removes Duplicates)
UNION ALL (Keeps Duplicates)
Rules for UNION
- Same number of columns: All SELECT statements must have the same number of columns
- Compatible data types: Corresponding columns must have compatible data types
- Column order: Columns are matched by position, not by name
- Column names: Result uses column names from the first SELECT
Basic UNION Examples
Combining Similar Tables
Combining Different Tables
UNION with WHERE Clause
UNION with ORDER BY
UNION with LIMIT
Multiple UNION Operations
UNION with Aggregates
UNION with Subqueries
UNION with JOIN
UNION with CASE
Practical Examples
Combining Search Results
Creating Reports
Combining Historical and Current Data
Creating Lookup Lists
Performance Considerations
UNION vs UNION ALL
Use UNION ALL when:
- You know there are no duplicates
- You want to keep duplicates
- Performance is critical
Use UNION when:
- You need to remove duplicates
- Data quality requires unique results
Indexing
Using EXPLAIN
Common Patterns
Deduplication Across Tables
Combining Partial Results
Creating Summary Rows
Best Practices
-
Use UNION ALL when possible for better performance
-
Ensure column compatibility
-
Use meaningful column names
-
Filter before UNION
-
Use parentheses for complex queries
Common Mistakes to Avoid
Summary
UNION operator key points:
- UNION: Combines results and removes duplicates
- UNION ALL: Combines results and keeps duplicates (faster)
- All SELECT statements must have:
- Same number of columns
- Compatible data types
- Columns matched by position
- ORDER BY applies to the entire result set
- Use UNION ALL when duplicates are not an issue
- Filter data before UNION for better performance