Oracle INTERSECT

Summary: in this tutorial, you will learn how to use the Oracle INTERSECT operator to compare two queries and returns rows that are output by both.

Introduction to Oracle INTERSECT operator

The Oracle INTERSECT operator compares the result of two queries and returns the distinct rows that are output by both queries.

The following statement shows the syntax of the INTERSECT operator:

SELECT column_list_1 FROM T1 INTERSECT SELECT column_list_2 FROM T2;
Code language: SQL (Structured Query Language) (sql)

Similar to the UNION operator, you must follow these rules when using the INTERSECT operator:

  • The number and the order of columns must be the same in the two queries.
  • The data type of the corresponding columns must be in the same data type group such as numeric or character.

Oracle INTERSECT illustration

Suppose we have two queries that return the T1 and T2 result set.

  • T1 result set includes 1, 2, 3.
  • T2 result set includes 2, 3, 4.

The intersect of T1 and T2 result returns 2 and 3. Because these are distinct values that are output by both queries.

The following picture illustrates the intersection of T1 and T2:

Oracle INTERSECT

The illustration showed that the INTERSECT returns the intersection of two circles (or sets).

Oracle INTERSECT example

See the following contacts and employees tables in the sample database.

contacts table
employees table

The following statement uses the INTERSECT operator to get the last names used by people in both contacts and employees tables:

SELECT last_name FROM contacts INTERSECT SELECT last_name FROM employees ORDER BY last_name;
Code language: SQL (Structured Query Language) (sql)

Note that we placed the ORDER BY clause at the last queries to sort the result set returned by the INTERSECT operator.

In this tutorial, you have learned how to use the Oracle INTERSECT operator to compare two queries and returns the distinct rows that are output by both queries.

Was this tutorial helpful?