The INTERSECT operator returns only the rows that appear in the result sets of both SELECT queries. It is the set-theoretic intersection — any row not present in both results is excluded. Like UNION, INTERSECT automatically removes duplicate rows from the output.
INTERSECT syntax
SELECT select_list FROM A
INTERSECT
SELECT select_list FROM B;
Both queries must return the same number of columns in the same order with compatible data types. To sort the result, add ORDER BY after the final query:
SELECT select_list FROM A
INTERSECT
SELECT select_list FROM B
ORDER BY sort_expression;
INTERSECT example
Find films that are both top-rated and most popular:
SELECT * FROM top_rated_films
INTERSECT
SELECT * FROM most_popular_films;
title | release_year
----------------+--------------
The Godfather | 1972
The Dark Knight| 2008
(2 rows)
Only the two films that appear in both tables are returned. Films exclusive to one table are excluded.
INTERSECT with ORDER BY
SELECT * FROM top_rated_films
INTERSECT
SELECT * FROM most_popular_films
ORDER BY release_year;
title | release_year
----------------+--------------
The Godfather | 1972
The Dark Knight| 2008
(2 rows)
INTERSECT vs INNER JOIN
Both can find common records, but they work differently:
- INTERSECT: compares entire rows for equality across two result sets. No join key needed. Automatically deduplicates.
- INNER JOIN: connects tables on a specific key and can return additional columns from each side. More flexible but requires a shared key column.
Prefer INTERSECT when both queries have the same column structure and you want exact row matching. Use INNER JOIN when you need to pull related columns from both tables or when the key columns differ.
Key tips for using INTERSECT
- INTERSECT always removes duplicates. Use
INTERSECT ALLto preserve duplicate rows, returning each common row as many times as it appears in the smaller count across both result sets. - Column names in the output are taken from the first
SELECT. Use aliases in the first query to control output column names. - All set operators (
UNION,INTERSECT,EXCEPT) have the same precedence and are evaluated left to right. Use parentheses to control evaluation order when mixing operators. - INTERSECT can be used with more than two queries: chain additional
INTERSECTclauses to find rows common across three or more result sets. - For large tables, an INNER JOIN on an indexed key may be faster than INTERSECT since INTERSECT must hash or sort the full result sets to find common rows.
Reference: PostgreSQL documentation — Combining Queries (UNION, INTERSECT, EXCEPT).