Rows common to two queries (INTERSECT)
Two queries, one INTERSECT, and the overlap comes out deduplicated without a self-join.
The task
You want the customers who placed at least one order over 500 dollars and also had at least one order returned. Two conditions on different rows, two queries, one overlap.
The snippet
Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.
SELECT customer_id
FROM orders
WHERE amount > 500
INTERSECT
SELECT customer_id
FROM orders
WHERE status = 'returned'
ORDER BY customer_id;
仕組み
INTERSECT returns the customer ids produced by both branches, deduplicated, so each id appears once no matter how many matching orders it has. The two queries must return the same number of columns with compatible types. INTERSECT runs on all five engines (MySQL only from 8.0.31); older MySQL can emulate it with the self-join plus DISTINCT below.
Variations
Self-join emulation
SELECT DISTINCT a.customer_id
FROM orders a
JOIN orders b ON b.customer_id = a.customer_id
WHERE a.amount > 500
AND b.status = 'returned';
Questions that come up
Does INTERSECT keep duplicates?
No. It is a set operator: duplicates are removed from both inputs and the result. INTERSECT ALL keeps multiplicity on PostgreSQL, MySQL 8.0.31+ and Oracle 21c+. SQL Server and SQLite reject INTERSECT ALL, so use a join there.
Keep reading
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.