Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Databases
  • SQL
  • MySQL
  • PostgreSQL
  • PL/SQL
  • MongoDB
  • SQL Cheat Sheet
  • SQL Interview Questions
  • MySQL Interview Questions
  • PL/SQL Interview Questions
  • Learn SQL and Database
Open In App
Next Article:
SQL Server ANY Operator
Next article icon

SQL Server INTERSECT Operator

Last Updated : 19 Jan, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In SQL Server, the INTERSECT operator is a kind of set operator that is used to combine the results of two SELECT statements and return rows which is common between them.

In this article, We will explore the syntax, key concepts, and practical examples of using the INTERSECT operator. Whether you are managing customer data, tracking orders, and handling student enrollments.

Here are some points that show the importance of the INTERSECT operator:

  • When you are trying to identify similar rows between 2 sets of data, the INTERSECT operator comes in handy.
  • Instead of writing complex WHERE clauses to find common rows between 2 sets with multiple conditions, the INTERSECT operator is used as an alternative.
  • It offers better performance compared to any other methods.
  • It improves the readability of the query in SQL.

Prerequisites

Make sure you understand the SQL SELECT statement and how to prepare the relevant tables or views before using the INTERSECT operator. Also, you have to make sure the columns you want to compare have matching data sets.

Key Concepts

Only the rows that are present in both result sets are returned by the INTERSECT function when it runs on two SELECT statements. The primary prerequisite is that the two SELECT queries must have the same amount of columns and data types.

SQL Server INTERSECT Operator

The SQL Server INTERSECT operator is a powerful tool that allows database developers and analysts to retrieve the common elements from two or more result sets. Unlike other set operators like UNION or EXCEPT, INTERSECT focuses on finding the shared rows among multiple queries.

Syntax:

Here's the basic syntax:

SELECT column1, column2, ...

FROM table1

INTERSECT

SELECT column1, column2, ...

FROM table2;

Examples of SQL Server INTERSECT Opeartor

Example 1: Retrieving Customer Orders Using SQL Server INTERSECT

Let's look at an example where you wish to retrieve customer orders from two tables: customers and orders. The INTERSECT operator can be used as follows,

Step 1: Create Tables

-- Create Customers table  CREATE TABLE Customers (      CustomerID INT PRIMARY KEY,      CustomerName VARCHAR(50)  );    -- Create Orders table  CREATE TABLE Orders (      OrderID INT PRIMARY KEY,      CustomerID INT,      OrderDate DATE  );    

Step 2: Insert Sample Data

-- Insert data into Customers table  INSERT INTO Customers (CustomerID, CustomerName)  VALUES      (1, 'Tony'),      (2, 'Steve'),      (3, 'Peter'),      (4, 'Bruce'),      (5, 'Clark');  

Currently, data about customers is contained in the Customers table, while data about orders placed by customers is contained in the Orders table.

Output:

Output
Output

-- Insert data into Orders table   INSERT INTO Orders (OrderID, CustomerID, OrderDate) VALUES     (1, 1, '2022-01-01'),       (2, 2, '2021-02-02'),       (3, 5, '2020-03-03'),       (4, 1, '2022-04-04'),       (5, 3, '2020-05-05');

Output:

output
Output

Step 3: Perform INTERSECT Operation

-- Find customers who have placed orders  SELECT CustomerID  FROM Customers  WHERE CustomerID IS NOT NULL  INTERSECT  SELECT CustomerID  FROM Orders  WHERE CustomerID IS NOT NULL;  

Output:

Intersect_Operator
Output

The output gives common data of column CustomerId in both table.

It didn't gives 104 because that is only in Customer table and not in Order table, also 101 repeat twice in Order table but it gives only one time.

Example 2: Identifying Enrolled Students Using SQL Server INTERSECT

Let's look at another example where we want to identify students who are enrolled in at least one course. We have two tables, Students and Courses. Follow the steps to perform the INTERSECT operation:

Step 1: Create Tables

-- Create Students table  CREATE TABLE Students (      StudentID INT PRIMARY KEY,      StudentName VARCHAR(50)  );      -- Create Courses table  CREATE TABLE Courses (      CourseID INT PRIMARY KEY,      StudentID INT,      CourseName VARCHAR(50)  );  

Step 2: Insert Sample Data

-- Insert data into Students table  INSERT INTO Students (StudentID, StudentName)  VALUES      (1, 'Harry'),      (2, 'Ron'),      (3, 'Hermione'),      (4, 'Draco');    

Currently, information on students is contained in the Students table, and details about courses and student enrollments are contained in the Courses table.

Output:

output
Output

-- Insert data into Courses table   INSERT INTO Courses (CourseID, StudentID, CourseName) VALUES       (11, 1, 'Herbology '),       (12, 3, 'Astronomy'),       (13, 4, 'Care of Magical Creatures'),     (14, 2, 'Alchemy'),     (15, 1, 'Defense Against the Dark Arts');

Output:

output
Output

Step 3: Perform INTERSECT Operation

-- Find students who are enrolled in at least one course  SELECT StudentID  FROM Students  WHERE StudentID IS NOT NULL  INTERSECT  SELECT StudentID  FROM Courses  WHERE StudentID IS NOT NULL;  

Output:

output
Output

The output gives common data of column StudentId in both table.

1 repeat twice in Course table but it gives only one time.

Conclusion

In conclusion, SQL Server's INTERSECT operator offers a strong tool for finding common records between two result sets. So, when you need to identify data that overlaps across two tables or queries, it is quite helpful. The examples that I provided i.e., dealing with customer orders or student enrollments is illustrating the real-world applications of this operator. Learning how to use the INTERSECT operator in SQL Server gives you a foundational ability for effective data analysis and a methodical way to find commonalities between various tables and queries.


Next Article
SQL Server ANY Operator
author
akashjha2671
Improve
Article Tags :
  • Geeks Premier League
  • SQL Server
  • Databases
  • Geeks Premier League 2023

Similar Reads

  • PL/SQL INTERSECT Operator
    The PL/SQL INTERSECT operator is a powerful SQL set operation that allows us to return only the rows that are common to two or more SELECT queries. Unlike UNION or UNION ALL, which combine the results of different queries, INTERSECT focuses on finding the overlap between them. In this article, We wi
    3 min read
  • 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
    4 min read
  • SQL Server EXCEPT Operator
    Structured Query Language also known as SQL is a tool for storing, managing, and manipulating relational databases. SQL Server is a popular relational database management system (RDBMS) developed by Microsoft, providing a variety of operators to perform different operations on given datasets. One su
    4 min read
  • SQLite Intersect Operator
    SQLite is a server-less database engine written in C programming language. It is developed by D. Richard Hipp in the year 2000. The main moto for developing SQLite is escaping complex database engines like MYSQL. It has become one of the most popular database engines as we use it in Television, Mobi
    5 min read
  • SQL Server ANY Operator
    In SQL Server there are many different types of Logical operators like ANY, AND, LIKE, EXISTS, NOT, IN, and BETWEEN. The logical operators are used to perform conditional checks in SQL Queries. These operators are very useful to filter and compare single or multiple data in SQL Queries. In this arti
    3 min read
  • SQL Server ALL Operator
    In SQL Server the logical operators are used to perform conditional checks in SQL Queries. There are many different types of Logical operators like ANY, AND, LIKE, EXISTS, NOT, IN, and BETWEEN in SQL Server. These operators are very useful to filter and compare single or multiple data in SQL Queries
    3 min read
  • Arithmetic Operators in SQL Server
    Arithmetic operators play a crucial role in performing mathematical calculations within SQL Server. These operators allow you to perform addition, subtraction, multiplication, division, and more on numeric data stored in your database tables. In this article, we'll explore the various arithmetic ope
    4 min read
  • PostgreSQL - IN operator
    The IN operator in PostgreSQL is a powerful and efficient tool used to filter records based on a predefined set of values. When used with the WHERE clause, it simplifies SQL queries and enhances readability, making it a key component of SQL query optimization for data retrieval and database manipula
    4 min read
  • Relational Operators in SQL Server
    In SQL Server, relational operators are used to compare values and establish relationships between data stored in tables. These operators allow us to perform logical comparisons to filter data based on specific conditions. Understanding relational operators is fundamental for querying and manipulati
    4 min read
  • PostgreSQL - EXISTS Operator
    The EXISTS operator in PostgreSQL is a powerful SQL feature used to check the existence of rows in a subquery. It is particularly useful when working with correlated subqueries, where the inner query depends on values from the outer query. The EXISTS operator returns true if the subquery returns at
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences