🚀
12. Set Operations
++++
Data Engineering
May 2026×7 min read

Combine compatible result sets with UNION and UNION ALL, and understand when duplicates should be removed or preserved.

12. Set Operations

Driptanil Datta
Driptanil DattaSoftware Developer

Set Operations

Set operations combine the results of multiple SELECT statements. In MySQL basics, the most common ones are UNION and UNION ALL.

UNION

UNION combines results and removes duplicate rows.

SELECT email
FROM customers
WHERE country = "USA"
 
UNION
 
SELECT email
FROM library_members
WHERE status = "active";

If the same email appears in both result sets, it appears once in the final result.

UNION ALL

UNION ALL combines results and keeps duplicates.

SELECT city
FROM customers
 
UNION ALL
 
SELECT city
FROM employees;

Use UNION ALL when duplicates are meaningful or when you do not need duplicate removal. It is usually faster than UNION.

Column compatibility

Each SELECT must return the same number of columns in the same order.

SELECT
  customer_id AS entity_id,
  "customer" AS entity_type,
  city
FROM customers
 
UNION ALL
 
SELECT
  employee_id AS entity_id,
  "employee" AS entity_type,
  office_city AS city
FROM employees;

The column names in the final output come from the first SELECT.

Sorting union results

Put ORDER BY at the end of the full set operation.

SELECT email
FROM customers
 
UNION
 
SELECT email
FROM library_members
 
ORDER BY email;

Use set operations when you are stacking similar result sets vertically. Use joins when you are combining related columns horizontally.

Drip

Driptanil Datta

Software Developer

Building full-stack systems, one commit at a time. This blog is a centralized learning archive for developers.

Legal Notes
Disclaimer

The content provided on this blog is for educational and informational purposes only. While I strive for accuracy, all information is provided "as is" without any warranties of completeness, reliability, or accuracy. Any action you take upon the information found on this website is strictly at your own risk.

Copyright & IP

Certain technical content, interview questions, and datasets are curated from external educational sources to provide a centralized learning resource. Respect for original authorship is maintained; no copyright infringement is intended. All trademarks, logos, and brand names are the property of their respective owners.

System Operational

© 2026 Driptanil Datta. All rights reserved.