Description
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.
Intersect Query

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.
Syntax
The syntax for the NTERSECT operator in SQL Server (Transact-SQL) is:
SELECT expression1, expression2, ... expression_n FROM tables [WHERE conditions] INTERSECT SELECT expression1, expression2, ... expression_n FROM tables [WHERE conditions];
Parameters or Arguments
- expressions
- 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.
- tables
- The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause.
- WHERE conditions
- Optional. The conditions that must be met for the records to be selected.
Note
- There must be same number of expressions in both SELECT statements.
- The corresponding columns in each of the SELECT statements must have similar data types.
- The INTERSECT operator returns only records in common between the SELECT statements.
Example - With Single Expression
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:
SELECT product_id FROM products INTERSECT SELECT product_id FROM inventory;
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.
Comments
Post a Comment