Sub topic 5
INTERSECT: rows present in both results
This chapter assumes you can write SELECT queries with WHERE, that you know DISTINCT and ORDER BY, and that you know a NULL means "no value". It also assumes you have seen why two queries must have compatible column lists before a set operator can combine them. INTERSECT takes two query results and keeps only the rows that appear in both.
What INTERSECT does
INTERSECT runs the query on its left and the query on its right. It then returns the rows that exist in both results, with duplicates removed.
SELECT email FROM customers
INTERSECT
SELECT email FROM newsletter_subscribers;This returns the distinct emails that appear in both customers and newsletter_subscribers. The result answers the question "which people are both customers and subscribers?"
Three properties define its behavior:
- It compares whole rows. Two rows match only if every column in the select list is equal.
- It removes duplicates. A row appears at most once in the output, even if it appears many times in each input.
- It is symmetric.
A INTERSECT Breturns the same rows asB INTERSECT A. Only the column names can differ, because the output takes its names from the first query.
A worked example
The following script builds small tables with a duplicate and a NULL on purpose. It uses only standard SQL, so it runs in PostgreSQL, SQLite, SQL Server, and recent versions of MySQL and MariaDB.
CREATE TABLE customers (email VARCHAR(100));
CREATE TABLE newsletter_subscribers (email VARCHAR(100));
INSERT INTO customers (email) VALUES
('[email protected]'),
('[email protected]'),
('[email protected]'),
('[email protected]'),
(NULL);
INSERT INTO newsletter_subscribers (email) VALUES
('[email protected]'),
('[email protected]'),
('[email protected]'),
(NULL);
SELECT email FROM customers
INTERSECT
SELECT email FROM newsletter_subscribers;The result contains three rows, in no guaranteed order:
| [email protected] |
| [email protected] |
| NULL |
Compare this with the inputs:
[email protected]is only incustomers, so it is dropped.[email protected]is only innewsletter_subscribers, so it is dropped.[email protected]appears twice incustomers, but appears once in the output.NULLis in the result. This surprises people, and the next section explains why.
How NULLs are matched
In a WHERE clause or a join condition, NULL = NULL evaluates to unknown, so the rows never match. Set operators use a different rule. They treat two NULL values as the same value when comparing rows. The SQL standard calls this "not distinct from" semantics. It is the same rule DISTINCT and GROUP BY use.
As a result, if both inputs contain at least one NULL in a column, the intersection contains one NULL row for that column. A join written as ON c.email = s.email would not return it. The "Equivalent queries" section below covers this difference.
For multi-column rows, the rule applies per column. The rows (1, NULL) and (1, NULL) are considered equal. The rows (1, NULL) and (1, 5) are not.
Matching on several columns
Because INTERSECT compares the whole row, adding columns makes the match stricter. Suppose both tables also have a city column:
SELECT email, city FROM customers
INTERSECT
SELECT email, city FROM newsletter_subscribers;A person who is in both tables but lives in different cities according to each table does not appear in the result. To match on email alone, select only email.
This leads to a common mistake. You cannot match on one column and also return extra columns from one side. If you add customer_id to the first query's select list, the rows can no longer match anything in a table that has no equal customer_id value. When you need other columns from the matching rows, use a join or EXISTS, covered below.
The same applies to literal columns. The UNION ALL example from earlier chapters added 'customer' AS source. Doing the same with INTERSECT would make every row differ between the two sides, and the result would be empty:
-- Returns no rows: 'customer' never equals 'subscriber'
SELECT email, 'customer' AS source FROM customers
INTERSECT
SELECT email, 'subscriber' AS source FROM newsletter_subscribers;Using INTERSECT with filters
Each side of an INTERSECT is a full query, so it can have its own WHERE, joins, and GROUP BY. That makes it a good fit for "which values satisfy both conditions" questions where the conditions come from different tables or different rows.
SELECT customer_id FROM orders WHERE product = 'laptop'
INTERSECT
SELECT customer_id FROM orders WHERE product = 'monitor';This returns the customers who have ordered both a laptop and a monitor. A single WHERE product = 'laptop' AND product = 'monitor' would return nothing, because one row has only one product. INTERSECT solves this by combining two separate row sets. The same question can also be answered with a self-join, a pair of EXISTS subqueries, or GROUP BY ... HAVING. INTERSECT is often the shortest to read.
Combining with ORDER BY
A single ORDER BY after the last query sorts the whole result. In many databases it must use column names or positions from the first query.
SELECT email FROM customers
INTERSECT
SELECT email FROM newsletter_subscribers
ORDER BY email;You cannot put a separate ORDER BY inside one side without wrapping that side in parentheses or a subquery. Sorting a side before an intersection has no effect anyway, because the operator does not preserve input order.
Combining with other set operators
When you mix INTERSECT with UNION or EXCEPT, evaluation order matters. In the SQL standard, INTERSECT binds more tightly than UNION and EXCEPT, as multiplication binds tighter than addition. PostgreSQL and SQL Server follow this. Oracle evaluates set operators from left to right with equal priority. Do not rely on memory of these rules. Parenthesize any query that mixes operators:
SELECT email FROM customers
UNION
(SELECT email FROM newsletter_subscribers
INTERSECT
SELECT email FROM webinar_attendees);The parentheses state the intended order, and the query returns the same rows on any system that supports the syntax.
Equivalent queries with joins and EXISTS
You can write an intersection without INTERSECT. Two common forms are an inner join and EXISTS.
SELECT DISTINCT c.email
FROM customers c
JOIN newsletter_subscribers s ON s.email = c.email;SELECT DISTINCT c.email
FROM customers c
WHERE EXISTS (
SELECT 1 FROM newsletter_subscribers s WHERE s.email = c.email
);Both queries drop the NULL row, because NULL = NULL is not true. On the sample data they return only [email protected] and [email protected]. INTERSECT returns the NULL row as well. If you need the NULL match, write the comparison to treat NULLs as equal. Some databases support IS NOT DISTINCT FROM for this:
SELECT DISTINCT c.email
FROM customers c
JOIN newsletter_subscribers s ON s.email IS NOT DISTINCT FROM c.email;IS NOT DISTINCT FROM is standard SQL and works in PostgreSQL, SQL Server 2022 and later, and others. MySQL uses the <=> operator instead. SQLite uses IS.
Use this table to choose between the forms:
| Situation | Better choice |
|---|---|
| Matching whole rows over the same columns, and you want a short, readable query | `INTERSECT` |
| You need columns from either table beyond the matched ones | Join or `EXISTS` |
| Your database lacks `INTERSECT` | Join or `EXISTS` |
| You want `NULL` values to match, with the least syntax | `INTERSECT` |
| You want `NULL` values not to match | Join or `EXISTS` |
| The match is on a key but other columns may differ | Join or `EXISTS` |
Common errors
- Different number of columns.
SELECT email, city ... INTERSECT SELECT email ...fails with an error about the number of columns. Both sides need the same count. - Incompatible types. Intersecting an integer column with a text column either fails or forces an implicit conversion, depending on the database. Cast one side explicitly, for example
CAST(id AS VARCHAR(20)). - Expecting a key match.
INTERSECTcompares every selected column. If you select extra columns that differ, you get fewer rows than you expect, or none. - Using it where it is unsupported. MySQL added
INTERSECTin version 8.0.31. Earlier MySQL versions give a syntax error, and you need a join orEXISTSthere. MariaDB has supported it since 10.3. - Expecting a particular order. Without
ORDER BYthe order of the output is undefined and can change between runs.
Summary of behavior
| Property | `INTERSECT` behavior |
|---|---|
| Rows returned | Rows present in both inputs |
| Duplicates | Removed from the result |
| `NULL` comparison | Two `NULL`s are treated as equal |
| Symmetry | `A INTERSECT B` returns the same rows as `B INTERSECT A` |
| Column names | Taken from the first query |
| Column requirements | Same count, compatible types, same positions |
Exercise
A table orders(customer_id, product) contains rows for customer 7 with products 'laptop', 'laptop', and 'monitor', and for customer 8 with product 'laptop' only. What does SELECT customer_id FROM orders WHERE product = 'laptop' INTERSECT SELECT customer_id FROM orders WHERE product = 'monitor' return, and how many times does that customer appear?
Show answer
It returns customer 7, exactly once. Customer 7 appears in both result sets. The duplicate 'laptop' rows do not matter, because INTERSECT removes duplicates. Customer 8 appears only in the first result, so it is dropped.
Exercise
Both customers and newsletter_subscribers contain a row with a NULL email. Does SELECT email FROM customers INTERSECT SELECT email FROM newsletter_subscribers include a NULL row, and does the equivalent query using JOIN ... ON s.email = c.email include one? Explain the difference.
Show answer
INTERSECT includes one NULL row, because set operators treat two NULLs as equal when comparing rows. The join does not include it, because the condition NULL = NULL evaluates to unknown, not true, so the rows never match. To make the join match NULLs, use a null-safe comparison such as IS NOT DISTINCT FROM (or <=> in MySQL).