MySQL 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 Syntax
UNION vs UNION ALL
UNION
UNION ALL
Comparison
| Aspect |-------------|-------|-----------| | Duplicates | Performance | Use case | Memory
Basic UNION
Same Number of Columns
Different Number of Columns
Column Types
UNION with WHERE
UNION and ORDER BY
UNION with LIMIT
Combining Multiple SELECTs
UNION with Subqueries
Practical Examples
Log Aggregation
Multi-Source Data
Data Deduplication
Time-Based Union
Performance Considerations
Index Usage
Query Optimization
UNION in Programming Languages
Python / Python
PHP / PHP
Summary
UNION operator provides:
- Result Combination: Merge multiple SELECT results
- Deduplication: UNION removes duplicates
- Performance: UNION ALL is faster
- Sorting: ORDER BY at the end
- Limitations: Same column count and compatible types
- Use Cases: Log aggregation, multi-source data
Previous: LIKE
Next: ORDER BY