UNION, INTERSECT, and EXCEPT

Combines result sets using UNION ALL, UNION, INTERSECT, and EXCEPT operators to merge, find common, or find differing rows between queries.

SqlData Fetching

Code

snippet
-- UNION ALL: combine with duplicates (faster)
SELECT 'customer' AS role, customer_id AS id, email
FROM customers
WHERE is_active = true
UNION ALL
SELECT 'employee' AS role, employee_id AS id, email
FROM employees
WHERE employment_status = 'active'
UNION ALL
SELECT 'supplier' AS role, supplier_id AS id, contact_email AS email
FROM suppliers
WHERE is_active = true
ORDER BY role, email;

-- INTERSECT: find customers who are also employees
SELECT email FROM customers
INTERSECT
SELECT email FROM employees;

-- EXCEPT: find customers who never placed an order
SELECT c.customer_id, c.first_name, c.last_name
FROM customers c
WHERE c.is_active = true
EXCEPT
SELECT o.customer_id, c.first_name, c.last_name
FROM orders o
JOIN customers c ON o.customer_id = c.customer_id
ORDER BY customer_id;

-- Combine aggregated results from different periods
SELECT 'Q1' AS quarter, SUM(amount) AS total
FROM sales WHERE sale_date BETWEEN '2025-01-01' AND '2025-03-31'
UNION ALL
SELECT 'Q2' AS quarter, SUM(amount) AS total
FROM sales WHERE sale_date BETWEEN '2025-04-01' AND '2025-06-30'
UNION ALL
SELECT 'Q3' AS quarter, SUM(amount) AS total
FROM sales WHERE sale_date BETWEEN '2025-07-01' AND '2025-09-30'
ORDER BY quarter;

What the code does

The file walks through SELECT statements over customers, employees, suppliers, orders and sales, each pairing tables with a different set operator.

Concretely, the SQL combines: one JOIN combining rows across tables; a WHERE clause that scopes which rows one statement can hit; SUM aggregation; an ORDER BY that fixes the output order; a UNION combining result sets from separate queries.

Using it

Run it in the customers database context.

Key statements

SELECT c.customer_id, c.first_name, c.last_name
FROM customers c
WHERE c.is_active = true
EXCEPT
SELECT o.customer_id, c.first_name, c.last_name
FROM orders o
JOIN customers c ON o.customer_id = c.customer_id
ORDER BY customer_id;
SELECT email FROM customers
INTERSECT
SELECT email FROM employees;

FAQ

What objects does the SQL involve?
`customers`, `employees`, `suppliers`, `orders`, `sales`, combined through a join.