In SQL, Set Operations allow us to combine the results of two or more queries. The most common set operations are:
π¨ Pro Tip: All set operations work by comparing the result sets row by row. Ensure that the columns in both queries have the same number and type of data.
The UNION operation combines the results of two queries but removes any duplicate rows from the final result.
Example: Get the distinct employees from both the Sales and Marketing departments:
SELECT employee_name FROM employees WHERE department = 'Sales' UNION SELECT employee_name FROM employees WHERE department = 'Marketing';
This query combines the employees from the Sales and Marketing departments without showing duplicates.
The UNION ALL operation is similar to UNION, but it does not remove duplicates, so all results are returned, including repeated rows.
Example: Get all employees from both the Sales and Marketing departments, including duplicates:
SELECT employee_name FROM employees WHERE department = 'Sales' UNION ALL SELECT employee_name FROM employees WHERE department = 'Marketing';
This query returns all employee names from both departments, even if some employees appear in both departments.
The INTERSECT operation returns the common rows from two queries. It essentially finds the intersection of two result sets.
Example: Get employees who work in both the Sales and Marketing departments:
SELECT employee_name FROM employees WHERE department = 'Sales' INTERSECT SELECT employee_name FROM employees WHERE department = 'Marketing';
This query returns only the employees who appear in both the Sales and Marketing departments.
The EXCEPT operation returns the rows from the first query that are not in the second query. Itβs like subtracting the second result set from the first.
Example: Get employees who are in the Sales department but not in the Marketing department:
SELECT employee_name FROM employees WHERE department = 'Sales' EXCEPT SELECT employee_name FROM employees WHERE department = 'Marketing';
This query returns employees who are in the Sales department but not in the Marketing department.
ORDER BY
clause.UNION ALL
may be faster than UNION
because it does not need to check for duplicates.
π― Interactive Task: Create queries using UNION
, UNION ALL
, INTERSECT
, and EXCEPT
to explore how different data sets combine and interact. Try using sample tables from your own database!
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!