Explain the use of the INTERSECT operator in SQL.
Instruction: Describe what the INTERSECT operator does and provide an example scenario where it could be used.
Updated
Official answer
INTERSECT returns result rows present in both input queries, removing duplicates unless a supported ALL form is requested. The inputs need equal column counts and compatible corresponding types.
For PostgreSQL:
SELECT customer_id FROM online_orders
INTERSECT
SELECT customer_id FROM store_orders
ORDER BY customer_id NULLS LAST;
If the inputs contain [1, 1, 2, NULL] and [1, 3, NULL], the result contains 1 and NULL once each. Set-operation duplicate comparison treats these NULL rows as matching; this differs from an ordinary NULL = NULL predicate, which is unknown.
This answers which customer IDs appear in both sources. It does not return order pairs or preserve order-level multiplicity. Select all columns that define the intended comparison; two rows sharing an ID but differing in another selected column are different result rows. Use an outer ORDER BY when order matters, and verify dialect support for INTERSECT ALL before using multiset intersection.