The INTERSECT operator is one of the set operations in SQL used to combine the result sets of two or more SELECT statements. The operator returns all rows that are present in both result sets. In other words, it returns the common rows present in all SELECT statements.
The basic syntax for using the INTERSECT operator is as follows:
SELECT column1, column2, ... FROM table1 INTERSECT SELECT column1, column2, ... FROM table2;
Here, the columns specified in the SELECT clause of both SELECT statements should be the same.
Let’s look at an example to better understand the use of the INTERSECT operator:
Suppose we have two tables
table2 with the following data:
table1: +----+-------+ | ID | Name | +----+-------+ | 1 | John | | 2 | Alice | | 3 | Bob | +----+-------+ table2: +----+-------+ | ID | Name | +----+-------+ | 1 | John | | 4 | Peter | | 3 | Bob | +----+-------+
Now, let’s say we want to find the names of the people who are present in both tables. We can use the following query:
SELECT Name FROM table1 INTERSECT SELECT Name FROM table2;
The result will be:
+-------+ | Name | +-------+ | John | | Bob | +-------+
In this example, we used the INTERSECT operator to combine the results of two SELECT statements that selected the Name column from the tables. The resulting set only contains the common names from both tables.
It is important to note that the INTERSECT operator only selects distinct rows that are present in both SELECT statements. If there are any duplicate rows in either of the tables, they will not be included in the final result set.
The INTERSECT operator is very useful in scenarios where we need to compare two or more tables and find common rows.
Also check WHAT IS GIT ? It’s Easy If You Do It Smart
You can also visite the Git website (https://git-scm.com/)