For working professionals
For fresh graduates
More
SQL Tutorial: Learn Structured…
1. SQL Tutorial
2. The Essential Guide To Understanding SQL In DBMS
3. SQL Commands
4. SQL Data Types
5. SQL Aliases
6. SQL INSERT INTO With Examples
7. Master SQL Update
8. SQL Delete Statement: A Complete Overview with Examples
9. SQL Delete Statement Example
10. SQL WHERE Clause
11. SQL AND Operator
12. SQL NOT Operator: A Comprehensive Guide
13. SQL Like
14. SQL Between Operator: A Complete Overview with Examples
15. Difference Between SQL and MySQL: Get to Know Your DBMS
16. MySQL Workbench
17. A Comprehensive Guide to MySQL Workbench Installation and Configuration
18. Mastering SQL: Your Comprehensive Guide to Becoming an SQL Developer
19. SQL CREATE TABLE With Examples
20. How To Add Columns In SQL: A Step-By-Step Guide
21. Drop Column in SQL: Everything You Need to Know
22. Index in SQL
23. Constraints in SQL: A Complete Guide with Examples
24. Schema in SQL
25. Entity Relationship Diagram (ERD) - A Complete Overview
26. Foreign Key in SQL with Examples
27. An Ultimate Guide to Understand all About Composite Keys in SQL
28. Normalization in SQL
29. Better Data Management: The Efficiency of TRUNCATE in SQL
30. Difference Between DELETE and TRUNCATE in SQL
31. SQL ORDER BY
32. SQL Not Equal Operator
33. SQL Intersect Operator: A Comprehensive Guide
Now Reading
34. SQL Union: Explained with Examples
35. SQL Case Statement Explained with Examples
36. Unleashing the CONCAT Function In SQL: String Manipulation Made Easy
37. Understanding and Mastering COALESCE in SQL
38. NVL in SQL
39. Understanding SQL Date Formats and Functions
40. DateDiff in SQL: A Complete Guide in 2024
41. SQL Wildcards
42. SQL DISTINCT: A Comprehensive Guide
43. LIMIT in SQL: A Comprehensive Tutorial
44. SQL Aggregate Functions
45. GROUP BY in SQL
46. SQL HAVING
47. EXISTS in SQL
48. SQL Joins
49. Inner Join in SQL
50. Left Outer Join in SQL
51. Full Outer Join in SQL
52. Cross Join in SQL
53. Self Join SQL
54. Left Join in SQL
55. Mastering SQL Substring
56. Understanding the ROW_NUMBER() Function in SQL
57. Cursor in SQL
58. Triggers In SQL
59. Stored Procedures in SQL
60. RANK Function in SQL
61. REPLACE in SQL
62. How to Delete Duplicate Rows in SQL
63. Transact-SQL
64. INSTR in SQL
65. PostgreSQL vs MySQL: Explore Key Differences
66. Mastering SQL Server Management Studio (SSMS): A Comprehensive Guide
67. Auto-Increment in SQL
68. Unveiling the Power of SQL with Python
69. SQL Vs NoSQL: Key Differences Explained
70. Advanced SQL
71. SQL Subquery
72. Second Highest Salary in SQL
73. Database Integrity Constraints: Everything You Need to Know
74. Primary Key In SQL: A Complete Guide in 2024
75. A Comprehensive Guide on View in SQL
76. Understanding PostgreSQL: A Complete Tutorial
77. SQL Injection Attack
78. MySQL database
79. What is SQLite
80. SQLite
81. ALTER Command in SQL
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.
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
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.
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 | CITY | |
1 | Alice | New York | |
2 | Bob | Los Angeles | |
3 | Charlie | Chicago | |
4 | David | San Francisco | |
5 | Emily | 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 | CITY | |
Alice | New York | |
Bob | Los Angeles | |
Charlie | Chicago | |
David | San Francisco | |
Emily | Seattle |
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.
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 |
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 | CITY | |
1 | Alice | New York | |
2 | Bob | Los Angeles | |
3 | Charlie | 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 | CITY | |
Alice | New York | |
Bob | Los Angeles |
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 |
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.
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.
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:
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; |
The INTERSECT command in SQL is a powerful tool for finding common records across multiple SELECT statements in various database systems
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;
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.
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.
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.
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.
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.