SQL UNION Function
Quick summary: The SQL UNION operator combines the result sets of two SELECT queries and removes duplicates.
SQL UNION Syntax
SELECT_statement1 UNION SELECT_statement2
SQL
SQL UNION Basic examples
SELECT email FROM users UNION SELECT email FROM admins;
SQL
Output:
Unique email list
Merges results without duplicates.
SQL UNION Real-world usage
SELECT id FROM active_users UNION SELECT id FROM pending_users;
SQL
Output:
Combined unique IDs
Combines datasets from different tables.
SQL UNION Edge cases
SELECT 1 UNION SELECT 1;
SQL
Output:
1
Duplicate rows are removed.
SQL UNION Common mistakes
Using UNION when duplicates are needed
UNION removes duplicates.
Incorrect
UNION
Correct
UNION ALL
Use UNION ALL to keep duplicates.
SQL UNION Frequently Asked Questions
What does UNION do in SQL?
Combines results and removes duplicates.
Use case of UNION?
Merging result sets.
Syntax?
SELECT ... UNION SELECT ...
Common mistake?
Mismatched columns.
Removes duplicates?
Yes.
Performance?
Slower due to deduplication.
Alternative?
UNION ALL.
Column count must match?
Yes.
Order guaranteed?
No.
Used in reporting?
Yes.
Supports ORDER BY?
Yes (final query).
Best practice?
Use UNION ALL when possible.