1. Home
SQL

SQL Tutorial: Learn Structured Query Language Basics

Learn all SQL tutorial concepts in detail and master your career today.

  • 59
  • 9 Hours
right-top-arrow

Tutorial Playlist

46 Lessons
32

SQL Intersect Operator: A Comprehensive Guide

Updated on 13/06/202441 Views

Introduction

Dating back to the early days of relational databases, SQL (Structured Query Language) has been instrumental in managing and querying data efficiently. Over time, as databases grew in complexity and size, developers sought more sophisticated ways to manipulate and retrieve data. This led to the development of various SQL operators, including the INTERSECT operator.

When you employ the INTERSECT operator in your SQL queries, you're essentially instructing the database to find the common ground between two result sets. It filters out any rows that aren't present in both sets, leaving you with only the data that meets the criteria specified in both SELECT statements.

To put it simply, if you have two sets of data and you want to identify the overlapping records, the INTERSECT operator is your go-to tool. Let's look into how this operator works and explore some practical examples to illustrate its functionality.

Overview

The SQL INTERSECT operator or command is a handy feature for database users. It enables you to extract data from the results of two separate SELECT statements. By using this operator, you can refine your queries to only include rows that are common between the two sets of results.

In this guide, let us explore how you can utilize the SQL INTERSECT operator to streamline your data retrieval process and obtain more precise information from your database. We will look at practical examples and much more

What Is the SQL INTERSECT Operator and How Does it Work?

The SQL INTERSECT operator in SQL is a powerful tool for refining your database queries by extracting only the rows in both of your SELECT statements.

Let's break down how it works.

It combines the rows of two SELECT statements and returns those rows from the first SELECT statement, which are the same as the rows of the second SELECT statement.

In simple words, we can say that this operator displays common rows from both the SELECT statements.

The INTERSECT operator or command in SQL is handy when you need to find common records present in multiple result sets. It ensures that only rows existing in all sets are returned, making it ideal for scenarios where you want to identify shared data points across different datasets

The following is the SQL syntax of the INTERSECT operator in Microsoft SQL Server −

SELECT column1, column2,...,

FROM table1, table2,...,

INTERSECT

SELECT column1, column2,...,

FROM table1, table2,...,

You should note that the data type and the number of fields must be the same for every SELECT statement used with the INTERSECT SQL operator.

Let’s look at a simple INTERSECT SQL example;

Let’s say you have two tables: one containing information about employees and another with details about their departments. Now, let's say you want to find out which employees belong to departments that exist in both tables.

You can use the INTERSECT operator to achieve this. It combines the results of two SELECT statements and returns only the rows that are common to both sets of results. In other words, it shows you the intersection of the data from the two SELECT statements.

Here is the INTERSECT query in SQL you would use:

SELECT employee_id, employee_name

FROM employees

INTERSECT

SELECT employee_id, employee_name

FROM department_employees;

This query will return the employee IDs and names of employees in both the "employees" table and the "department_employees" table.

A Practical Example of the SQL INTERSECT Operator

Let's consider a practical scenario in which we have two tables representing customers and their orders in an online retail store. We'll name the tables CUSTOMERS and ORDERS.

First, we create the CUSTOMERS table with fields such as ID, NAME, EMAIL, and CITY:

CREATE TABLE CUSTOMERS (

   ID INT NOT NULL,

   NAME VARCHAR(50) NOT NULL,

   EMAIL VARCHAR(50) NOT NULL,

   CITY VARCHAR(50) NOT NULL,

   PRIMARY KEY(ID)

);

We'll populate the CUSTOMERS table with sample data using INSERT:

INSERT INTO CUSTOMERS VALUES

(1, 'Alice', 'alice@example.com', 'New York'),

(2, 'Bob', 'bob@example.com', 'Los Angeles'),

(3, 'Charlie', 'charlie@example.com', 'Chicago'),

(4, 'David', 'david@example.com', 'San Francisco'),

(5, 'Emily', 'emily@example.com', 'Seattle');

Here is the customers table we just created

ID

NAME

EMAIL

CITY

1

Alice

alice@example.com

New York

2

Bob

bob@example.com

Los Angeles

3

Charlie

charlie@example.com

Chicago

4

David

david@example.com

San Francisco

5

Emily

emily@example.com

Seattle

Next, we create the ORDERS table to store order information:

CREATE TABLE ORDERS (

   ORDER_ID INT NOT NULL,

   CUSTOMER_ID INT NOT NULL,

   PRODUCT VARCHAR(50) NOT NULL,

   ORDER_DATE DATE NOT NULL,

   PRIMARY KEY(ORDER_ID)

);

Let's insert some sample data into the ORDERS table:

INSERT INTO ORDERS VALUES

(1, 1, 'Laptop', '2024-03-01'),

(2, 2, 'Smartphone', '2024-03-02'),

(3, 3, 'Tablet', '2024-03-03'),

(4, 4, 'Headphones', '2024-03-04'),

(5, 5, 'Speaker', '2024-03-05');

 Here is the ORDERS table we just created

ORDER_ID

CUSTOMER_ID

PRODUCT

ORDER_DATE

1

1

Laptop

2024-03-01

2

2

Smartphone

2024-03-02

3

3

Tablet

2024-03-03

4

4

Headphones

2024-03-04

5

5

Speaker

2024-03-05

Now, let's say we want to find out which customers have placed orders. We can use the INTERSECT operator to achieve this:

SELECT NAME, EMAIL, CITY FROM CUSTOMERS

INTERSECT

SELECT NAME, EMAIL, CITY FROM CUSTOMERS WHERE ID IN (SELECT DISTINCT CUSTOMER_ID FROM ORDERS);

This query selects the names, emails, and cities from the CUSTOMERS table where the customer IDs intersect with the customer IDs who have placed orders. Here's the output:

NAME

EMAIL

CITY

Alice

alice@example.com

New York

Bob

bob@example.com

Los Angeles

Charlie

charlie@example.com

Chicago

David

david@example.com

San Francisco

Emily

emily@example.com

Seattle

Using SQL Intersect Operator With Other Subqueries

Using the SQL INTERSECT operator alongside other subqueries can significantly enhance your ability to extract precise data from your database. Let's explore two scenarios where the INTERSECT operator is coupled with other operators to achieve specific results.

1. Using SQL INTERSECT with BETWEEN Operator

You can employ the INTERSECT operator in conjunction with the BETWEEN operator to pinpoint records falling within a designated range.

Suppose you have two tables: EMPLOYEES and SALARY. You want to find employees whose salaries fall within a certain range in both tables.

EMPLOYEES TABLE

ID

NAME

AGE

DEPARTMENT

1

Alice

30

HR

2

Bob

35

Sales

3

Charlie

28

Marketing

SALARY TABLE 

ID

EMPLOYEE_ID

SALARY

1

1

50000

2

2

55000

3

3

60000

SELECT NAME, AGE, DEPARTMENT FROM EMPLOYEES

WHERE AGE BETWEEN 25 AND 35

INTERSECT

SELECT E.NAME, E.AGE, E.DEPARTMENT FROM EMPLOYEES E

JOIN SALARY S ON E.ID = S.EMPLOYEE_ID

WHERE S.SALARY BETWEEN 50000 AND 60000;

This query returns employees aged between 25 and 35 and whose salaries fall between $50,000 and $60,000. Here is the output:

NAME

AGE

DEPARTMENT

Alice

30

HR

Bob

35

Sales

2. Using SQL INTERSECT with IN Operator

Another powerful combination involves the INTERSECT operator and the IN operator. The IN operator filters a result set based on a specified list of values. Here's an example:

Suppose you have two tables: CUSTOMERS and ORDERS. You want to find customers who have placed orders for specific products in both tables.

CUSTOMERS TABLE

ID

NAME

EMAIL

CITY

1

Alice

alice@example.com

New York

2

Bob

bob@example.com

Los Angeles

3

Charlie

charlie@example.com

Chicago

ORDERS TABLE 

ORDER_ID

CUSTOMER_ID

PRODUCT

ORDER_DATE

1

1

Laptop

2024-03-01

2

2

Smartphone

2024-03-02

3

3

Tablet

2024-03-03

SELECT NAME, EMAIL, CITY FROM CUSTOMERS

WHERE CITY IN ('New York', 'Los Angeles')

INTERSECT

SELECT C.NAME, C.EMAIL, C.CITY FROM CUSTOMERS C

JOIN ORDERS O ON C.ID = O.CUSTOMER_ID

WHERE O.PRODUCT IN ('Laptop', 'Smartphone');

This query returns customers from New York or Los Angeles who have placed orders for either a Laptop or Smartphone. Here is the output 

NAME

EMAIL

CITY

Alice

alice@example.com

New York

Bob

bob@example.com

Los Angeles

3. SQL INTERSECT with LIKE Operator

When you're dealing with SQL queries, leveraging the INTERSECT operator along with subqueries can provide powerful insights into your data. One interesting application is combining INTERSECT with the LIKE operator for pattern matching, which allows you to find common rows that match a specified pattern across tables.

For instance, suppose you're managing data for a university, and you have two tables: one containing student details (STUDENTS_HOBBY) and another with course information (STUDENTS). Let's explore how you can use INTERSECT along with LIKE to find students whose names start with a particular letter.

Imagine you want to identify students whose names begin with 'V'. You can utilize the LIKE operator with the wildcard % to match any sequence of characters after 'V'. Combining this with INTERSECT, you can find common names from both tables that satisfy this pattern.

SELECT NAME, AGE, HOBBY FROM STUDENTS_HOBBY

WHERE NAME LIKE 'V%'

INTERSECT

SELECT NAME, AGE, HOBBY FROM STUDENTS

WHERE NAME LIKE 'V%';

The output of this query would give you students whose names begin with 'V' and their corresponding ages and hobbies. For instance, you will get a result like:

NAME

AGE

HOBBY

Varun

26

Football

4. Using SQL INTERSECT Operator with WHERE Clause

Integrating the INTERSECT operator with the WHERE clause enables you to narrow down your dataset by intersecting the results of subqueries that filter data based on specific conditions. This approach is particularly useful when you need to identify records that meet certain criteria across multiple tables or conditions.

Let’s say you're managing a database for an e-commerce platform. You have two tables: one containing customer data (CUSTOMERS) and another with product information (PRODUCTS). Now, let's say you want to find customers who have purchased products from a certain category. Here's how you can use the INTERSECT operator with the WHERE clause:

SELECT customer_id FROM orders WHERE product_id IN (SELECT product_id FROM products WHERE category = 'Electronics')

INTERSECT

SELECT customer_id FROM orders;

In this example, the subquery (SELECT product_id FROM products WHERE category = 'Electronics') retrieves the product IDs of items in the Electronics category. The main query then finds customers who have purchased products from that category, intersecting this result with all customers who have placed orders.

5. Using SQL INTERSECT Operator with ORDER BY Clause

Combining the INTERSECT operator with the ORDER BY clause allows you to refine your dataset by intersecting the results of subqueries while maintaining a specific sorting order. This technique is valuable for scenarios where you need to identify top-performing records or prioritize certain data based on defined criteria.

Now, let's consider a scenario where you want to retrieve a list of customers who have made the highest number of purchases. You can achieve this by combining the INTERSECT operator with the ORDER BY clause:

SELECT customer_id, COUNT(*) AS num_orders FROM orders GROUP BY customer_id ORDER BY num_orders DESC

INTERSECT

SELECT customer_id, COUNT(*) AS num_orders FROM orders GROUP BY customer_id ORDER BY num_orders DESC LIMIT 1);

In this example, the first subquery retrieves the customer IDs along with the count of their orders, sorted in descending order of the number of orders. The second subquery limits the result to only the customer with the highest number of orders. By intersecting these two sets of data, you obtain the customer(s) with the highest number of orders.

Comparing SQL INTERSECT Operator to Other Similar SQL Commands

Other similar SQL commands like UNION, UNION ALL, EXCEPT, and JOIN also exist. When deciding which command to use, consider the specific requirements of your query:

  • Use INTERSECT when you need to find common records present in multiple result sets, ensuring that only rows existing in all sets are returned.
  • Use UNION when you want to combine the results of multiple queries into a single result set, removing duplicate entries by default.
  • Use UNION ALL when you need to combine results from multiple queries while retaining duplicate rows.
  • Use EXCEPT when you want to retrieve records from the first result set that are not present in the second result set.
  • Use JOIN when you need to retrieve data from multiple tables based on a related column between them.

Command

Description

Syntax

INTERSECT

Retrieves similar records from two or more SELECT queries. It only returns rows that occur in all of the result sets.

SELECT column1 FROM table1 INTERSECT SELECT column1 FROM table1;

UNION

Combines the outcomes of multiple SELECT operations into one collection. It removes duplicate rows by default.

SELECT column1, column2 FROM table1 UNION SELECT column1, column2 FROM table1;

UNION ALL

Like UNION, it combines the results of two or more SELECT queries into a single result set. However, it retains all rows, including duplicates.

SELECT column1, column2 FROM table1 UNION ALL SELECT column1, column2 FROM table1;

EXCEPT

Retrieves the distinct rows from the first SELECT statement that are not present in the result set of the second SELECT statement.

SELECT column1, column2 FROM table1 EXCEPT SELECT column1, column2 FROM table1;

JOIN

Combines rows from two or more tables depending on a common column between them. It lets you obtain data from numerous tables at once.

SELECT column1, column2 FROM table_t1 INNER JOIN tablet1 ON table_t1.column1 = table1_t1.column1;

SQL INTERSECT Operator on Different Database Systems

The INTERSECT command in SQL is a powerful tool for finding common records across multiple SELECT statements in various database systems

1. SQL Server

In SQL Server, you can use it to retrieve intersecting data sets efficiently. The syntax is

SELECT column1, column2, ...

FROM table1

INTERSECT

SELECT column1, column2, ...

FROM table2;

2. MySQL

Intersect in MySQL is not directly a supported command, but you can achieve similar functionality using a combination of INNER JOIN and GROUP BY or by using subqueries.

3. PostgreSQL

In PostgreSQL, INTERSECT works similarly to SQL Server, providing a straightforward way to find common rows. It has the same syntax as in the SQL server. 

Conclusion

In conclusion, the SQL INTERSECT operator stands out as a powerful tool for refining database queries by extracting only the rows shared between two or more SELECT statements. It efficiently filters out any rows not present in all sets, making it ideal for pinpointing common data points across different datasets.

The INTERSECT operator enables you to identify overlapping records accurately. This is true whether you're managing customer databases or analyzing orders in an online store.

By understanding its functionality and versatility, you can streamline your data retrieval process and extract valuable insights from your database with ease.

Frequently Asked Questions

1. What is join vs INTERSECT in SQL?

A join combines rows from different tables based on a related column, while INTERSECT retrieves common rows from multiple SELECT statements.

2. How do you order by INTERSECT in SQL?

You can order the results of INTERSECT by wrapping the entire query in parentheses and adding an ORDER BY clause at the end.

3. What is an example of INTERSECT?

An example of INTERSECT is finding common records between two tables, such as customers who appear in both a "customers" table and an "orders" table.

4. Does SQL INTERSECT remove duplicates?

Yes, SQL INTERSECT removes duplicates by default, ensuring that only unique rows common to all SELECT statements are returned.

5. Why use INTERSECT SQL?

INTERSECT SQL is used to extract common data points from multiple result sets, helping to identify shared records across different datasets accurately.

6. What is the difference between INTERSECT and bisect?

INTERSECT retrieves common rows from multiple SELECT statements, while bisect is not an SQL operator; it's a mathematical term that refers to dividing something into two equal parts.

7. What is the limit of INTERSECT in SQL?

There is no specific limit to the number of rows that INTERSECT can handle in SQL; it depends on the capabilities and constraints of the database system being used.

8. What is the opposite of INTERSECT in SQL?

The opposite of INTERSECT in SQL is EXCEPT, which retrieves rows from the first SELECT statement that are not present in the result set of the second SELECT statement.

9. What is the difference between union and INTERSECT?

UNION combines the results of two or more SELECT statements, including duplicates, while INTERSECT retrieves common rows from multiple SELECT statements, removing duplicates by default.

10. What is the intersection function?

The intersection function, typically used in set theory or mathematics, refers to the common elements between two or more sets. In SQL, INTERSECT serves a similar purpose by retrieving common rows from multiple SELECT statements.

Ankit Mittal

Ankit Mittal

Senior Software Engineer

Working as an Senior Software Engineer at upGrad, with proven experience across various industries. 

Get Free Career Counselling
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...