How does SQL perform operations such as union, intersection, and difference on sets?
In SQL, operators like UNION, INTERSECT, and EXCEPT can be used to perform set operations such as union, intersection, and difference.
- Union operation: Combines the result sets of two or more SELECT statements into one result set, removing duplicate rows.
For example: - Retrieve column1 and column2 from both table1 and table2 and combine the results.
- Intersection operation (INTERSECT): Returns the rows that are present in the result set of two or more SELECT statements, without removing duplicates.
For example: - Retrieve the items that are the same in both table1 and table2 for columns column1 and column2.
- Difference operation (EXCEPT): Returns the rows that are in the result set of the first SELECT statement but not in the result set of the second SELECT statement, without removing duplicates. For example:
- Retrieve column1 and column2 from table1, excluding any matching rows from table2.
The above operators can be nested as needed to achieve a combination of multiple operations.