SQL•Set Operations
SQL Set Operations: UNION, UNION ALL, and INTERSECT
UNION combines results and removes duplicates; UNION ALL preserves duplicates and is significantly faster.
Syntax
SELECT col FROM tableA UNION ALL SELECT col FROM tableB;
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| UNION | Set Operator | Combines queries and performs deduplication. |
| UNION ALL | Set Operator | Combines queries without deduplication (higher performance). |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing SQL locally:
CREATE TABLE direct_clients (email TEXT);
CREATE TABLE partner_clients (email TEXT);
INSERT INTO direct_clients VALUES
('[email protected]'),
('[email protected]');
INSERT INTO partner_clients VALUES
('[email protected]'),
('[email protected]');
-- UNION combines and removes duplicate '[email protected]'
SELECT email, 'Unified Client' AS source FROM direct_clients
UNION
SELECT email, 'Unified Client' AS source FROM partner_clients;Expected Output:
email source --------------- -------------- [email protected] Unified Client [email protected] Unified Client [email protected] Unified Client
How It Works: Step-by-Step
- Lines 1-10: Creates two client tables sharing a duplicate entry.
- Lines 13-15: UNION returns distinct set of all 3 unique emails.
Key Concepts
- UNION sorts and deduplicates the merged result set.
- Prefer UNION ALL when you know result sets are disjoint or duplicates are acceptable.
Common Mistake: Using UNION instead of UNION ALL when duplicates are not possible
UNION incurs an expensive sorting/deduplication step that slows down large datasets.
❌ Incorrect
SELECT id FROM table_a UNION SELECT id FROM table_b;
✅ Correct
SELECT id FROM table_a UNION ALL SELECT id FROM table_b;
Related SQL Tutorials & Compiler
SQL INNER JOIN and LEFT JOIN: Combining Relational Tables
Combine related data across tables using INNER JOIN and LEFT OUTER JOIN with ON keys.
SQL Subqueries: Correlated and Non-Correlated Subqueries
Nest queries within queries in WHERE, FROM, and SELECT clauses.
SQL Dynamic Transactional CASE WHEN Metrics Query Logic
Implement dynamic transactional business logic and classification metrics in SQL using CASE WHEN expressions.
SQL Online Compiler
Open in Compilra IDE
Run and test SQL on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.