In this post explains how to use the INTERSECT operator in SQL Server (Transact-SQL) with syntax and examples.
The SQL Server (Transact-SQL) INTERSECT operator is used to return the records that are in common between two SELECT statements or data sets. If a record exists in one query and not in the other, it will be omitted from the INTERSECT results. It is the intersection of the two SELECT statements.
Explanation: The INTERSECT query will return the records in the blue shaded area. These are the records that exist in both Dataset1 and Dataset2.
Each SELECT statement within the SQL Server INTERSECT must have the same number of columns in the result sets with similar data types.
The syntax for the INTERSECT operator in SQL Server (Transact-SQL) is:
The columns or calculations that you wish to compare between the two SELECT statements. They do not have to be the same fields in each of the SELECT statements, but the corresponding columns must be similar data types.
The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause.
Optional. The conditions that must be met for the records to be selected.
Let's look at an example of an INTERSECT query in SQL Server (Transact-SQL) that returns one column with the same data type.
For example:
In this INTERSECT example, if a product_id appeared in both the products and inventory tables, it would appear in your result set for this INTERSECT query.
Now, let's complicate our example further by adding WHERE conditions to the INTERSECT query.
In this example, the WHERE clauses have been added to each of the datasets. The first dataset has been filtered so that only records from the products table where the product_id is greater than or equal to 50 are returned. The second dataset has been filtered so that only records from the inventory table are returned where the quantity is greater than 0.
Next, let's look at an example of an INTERSECT query in SQL Server (Transact-SQL) that returns more than one column.
For example:
In this INTERSECT example, the query will return the intersection of the two SELECT statements. So if there are records in the contacts table with a contact_id, last_name, and first_name value that matches the employee_id, last_name, and first_name value in the employees table, the INTERSECT query will return these records. If there is no match, then the INTERSECT will not return the record.
Finally, let's look at how to use the ORDER BY clause in an INTERSECT query in SQL Server (Transact-SQL).
For example:
Since the column names are different between the two SELECT statements, it is more advantageous to reference the columns in the ORDER BY clause by their position in the result set. In this example, we've sorted the results by supplier_name / company_name in ascending order, as denoted by the ORDER BY 2.
The supplier_name / company_name fields are in position #2 in the result set.