SQL:SQL Set Operations: UNION, UNION ALL, and INTERSECT
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:

ParameterTypeDescription
UNIONSet OperatorCombines queries and performs deduplication.
UNION ALLSet OperatorCombines queries without deduplication (higher performance).

Ready-to-Run Code Example

Executable in Compilra

Run 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

Run and test SQL on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

SQL Online Compiler