SQL provides powerful set operations that allow combining results from multiple queries. Three key operations—UNION, INTERSECT, and EXCEPT—help in merging, filtering, and subtracting data efficiently. These operations simplify complex queries and improve data retrieval efficiency.
The UNION operator combines the results of two or more SELECT queries into a single result set, removing duplicate records by default.
SELECT column_names FROM table1
UNION
SELECT column_names FROM table2;SELECT name FROM Customers
UNION
SELECT name FROM Suppliers;This query retrieves unique names from both Customers and Suppliers tables.
If duplicates should be included, use UNION ALL:
SELECT name FROM Customers
UNION ALL
SELECT name FROM Suppliers;The INTERSECT operator returns only the common records present in both queries.
SELECT column_names FROM table1
INTERSECT
SELECT column_names FROM table2;SELECT name FROM Customers
INTERSECT
SELECT name FROM Suppliers;This query fetches names that exist in both Customers and Suppliers.
The EXCEPT operator returns the records from the first query that are not present in the second query.
SELECT column_names FROM table1
EXCEPT
SELECT column_names FROM table2;SELECT name FROM Customers
EXCEPT
SELECT name FROM Suppliers;This query retrieves names present in Customers but not in Suppliers.
UNION removes duplicates unless UNION ALL is used.INTERSECT and EXCEPT may not be supported in all database systems.SQL set operations—UNION, INTERSECT, and EXCEPT—offer efficient ways to manipulate and compare datasets across tables. Understanding these operations helps in building optimized queries for data analysis and reporting.
Sign in to join the discussion and post comments.
Sign in