- SQL Basics
- SQL Introduction
- SQL Syntax
- SQL Sample Database
- SQL SELECT
- SQL WHERE
- SQL ORDER BY
- SQL DISTINCT
- SQL LIMIT
- SQL FETCH
- SQL AND
- SQL OR
- SQL BETWEEN
- SQL IN
- SQL LIKE
- SQL IS NULL
- SQL Comparison Operators
- SQL Logical Operators
- SQL Alias
- SQL CASE
- Joins and Subqueries
- SQL INNER JOIN
- SQL LEFT JOIN
- SQL RIGHT JOIN
- SQL FULL OUTER JOIN
- SQL SELF JOIN
- SQL CROSS JOIN
- SQL Subquery
- SQL Correlated Subquery
- SQL UNION
- SQL INTERSECT
- SQL EXCEPT
- Aggregate Functions
- SQL AVG
- SQL COUNT
- SQL MAX
- SQL MIN
- SQL SUM
- SQL GROUP BY
- SQL HAVING
- SQL ROLLUP
- SQL CUBE
- SQL GROUPING SETS
- Database Management
- SQL CREATE DATABASE
- SQL ALTER DATABASE
- SQL DROP DATABASE
- SQL BACKUP DATABASE
- SQL SHOW DATABASES
- SQL SELECT DATABASE
- Table Management
- SQL CREATE TABLE
- SQL ALTER TABLE
- SQL ADD COLUMN
- SQL DROP COLUMN
- SQL DROP TABLE
- SQL TRUNCATE TABLE
- SQL SHOW TABLES
- SQL RENAME TABLE
- SQL Constraints
- SQL Primary Key
- SQL Foreign Key
- SQL UNIQUE Constraint
- SQL CHECK Constraint
- SQL NOT NULL Constraint
SQL INTERSECT
The INTERSECT operator in SQL is a set operator used to find the "common ground" between two datasets. It returns only the rows that are present in the result sets of both SELECT queries. Think of it as a mathematical intersection in a Venn diagram: only the overlapping area where both circles meet is returned.
While a UNION combines everything and a EXCEPT (or MINUS) finds differences, INTERSECT is your go-to tool when you need to identify records that satisfy two different sets of criteria simultaneously across different tables or queries.
INTERSECT when you need to perform data validation or find overlapping records between a production table and a backup/archive table.
Syntax of SQL INTERSECT
SELECT column1, column2, ...
FROM table1
WHERE condition
INTERSECT
SELECT column1, column2, ...
FROM table2
WHERE condition;
- SELECT statements: These are the standard queries you want to compare. You can include
WHEREclauses,GROUP BY, and joins within these individual statements. - INTERSECT: This keyword tells the database engine to compare the results of the top query with the bottom query and only keep the duplicates found in both.
- columns: For
INTERSECTto work, bothSELECTstatements must have the exact same number of columns in the same order.
INT, the first column in Query B must also be an INT (or a type that can be implicitly converted).
Key Points
- Automatic Deduplication: By default,
INTERSECTreturns unique rows. If a row appears multiple times in both tables, it will only appear once in the final result. - Column Alignment: The names of the columns in the final result set are usually taken from the first
SELECTstatement. - Performance: Large intersections can be resource-intensive. Ensure the columns you are intersecting are indexed if you are working with millions of rows.
- Comparison: Unlike a
JOIN, which combines columns horizontally,INTERSECTcompares rows vertically.
INTERSECT. For example, MySQL and MariaDB do not have a built-in INTERSECT operator. In those systems, you would achieve the same result using an INNER JOIN or an IN clause.
Example of SQL INTERSECT
Imagine you are managing a large organization and you have two different lists of employees: those who worked on "Project A" and those who worked on "Project B." You want to find out which "rockstar" employees contributed to both projects.
Table 1: Employees (Department A)
Table 2: Employees (Department B)
To find the employees present in both lists, we use the following query:
SELECT name, department
FROM employees_1
INTERSECT
SELECT name, department
FROM employees_2;
Output:
Explanation:
- The database looks at the first set (John, Alice, Bob) and the second set (Alice, Bob, Sarah).
- It identifies that only **Alice** and **Bob** exist in both results.
- **John** is excluded because he is only in Department A.
- **Sarah** is excluded because she is only in Department B.
SQL INTERSECT with Conditions
In real-world applications, you rarely want to intersect entire tables. Usually, you are looking for a specific subset. For instance, you might want to find customers who are both "Subscribed to the Newsletter" AND "Have made a purchase in the last 30 days."
SELECT email
FROM newsletter_subscribers
WHERE status = 'active'
INTERSECT
SELECT email
FROM orders
WHERE order_date >= '2023-10-01';
Here is another example using our employee tables, focusing specifically on the HR department:
SELECT name, department
FROM employees_1
WHERE department = 'HR'
INTERSECT
SELECT name, department
FROM employees_2
WHERE department = 'HR';
Output:
INTERSECT ALL. Standard INTERSECT performs an implicit DISTINCT.
Summary
The INTERSECT operator is a powerful way to filter data by finding matches across two different queries. It simplifies complex logic that would otherwise require nested joins or subqueries. Remember these three Golden Rules for using INTERSECT:
- The number of columns must match in both
SELECTstatements. - The data types of those columns must be compatible.
- The final result will automatically remove duplicate rows.