INTERSECT Operator in SQL Server

The INTERSECT operator is one of the Set Operators in SQL Server which is used to filter out duplicates and return only distinct rows of data. The INTERSET operator combines two or more SELECT statements and returns a single dataset with common and distinct data between the SELECT statements on the right and the left of the INTERSECT operator.

INTERSECT Syntax:

{ <query_specification> | ( <query_expression> ) }

{ INTERSECT }

{ <query_specification> | ( <query_expression> ) }

  • query_specification or query_expression is a SELECT statement with or without a where clause.
  • INTERSECT is the operator used to filter distinct or unique data common to the queries specified.

SQL Server INTERSECT and EXCEPT Operator

Multiple SQL Queries may return duplicate values in recordsets from each query result. There could be situations when a single resultset is needed to be returned by combining multiple SQL queries. In SQL Server, there are many SET operators like UNION, EXCEPT, and INTERSECT to merge multiple results of select statements to a single result set. The INTERSECT operator is one of them which is used to filter distinct values.

Structured Query Language (SQL) is a powerful tool for managing and manipulating relational databases. In SQL Server, various operators allow you to perform different types of set operations on your data. Two such operators are EXCEPT and INTERSECT, which are used to compare and combine the results of two queries.

Similar Reads

INTERSECT Operator in SQL Server

The INTERSECT operator is one of the Set Operators in SQL Server which is used to filter out duplicates and return only distinct rows of data. The INTERSET operator combines two or more SELECT statements and returns a single dataset with common and distinct data between the SELECT statements on the right and the left of the INTERSECT operator....

EXCEPT Operator

EXCEPT keyword is an operator that is used to retrieve distinct rows from the left query result set that are not present in the right query result set in a given query. It can be useful in finding the difference between two sets of data. The syntax for the EXCEPT operator is given as follows...

Examples of SQL Server INTERSECT and EXCEPT Operator

There are 3 tables used in the examples below and the queries to create tables and insert data are given below:...

Conclusion

In SQL Server, the INTERSECT and EXCEPT operators are used to get the common rows of two SELECT statements. The first SELECT statement retrieves the rows that are common to both SELECT statements. The second SELECT statement retrieves different rows that are not common to the two SELECT statements. These operators help to compare and analyze the data between two pairs of results in an SQL query....