Sub topic 2
INTERSECT: Rows Present in Both Results
This chapter assumes you can write SELECT with WHERE, you know what DISTINCT does, and you understand that NULL marks a missing value. The examples use two tables, customers and newsletter_subscribers, and an unsubscribed table. Each has an email column.
INTERSECT: Rows Present in Both Results
INTERSECT combines two SELECT statements and returns only the distinct rows that appear in both results. Both queries must return the same number of columns, with compatible types.
SELECT email FROM customers
INTERSECT
SELECT email FROM newsletter_subscribers;The result lists each email that is both a customer and a subscriber. Each email appears once, even if either table stores it several times.
EXCEPT: Rows in the First Result but Not the Second
EXCEPT returns the distinct rows from the first query that do not appear in the second. Order matters. Swapping the two queries changes the answer.
SELECT email FROM newsletter_subscribers
EXCEPT
SELECT email FROM unsubscribed;This query returns subscribers who have not unsubscribed. Oracle calls this operator MINUS.
How NULLs and Duplicates Are Treated
Set operators remove duplicate rows from their result by default. INTERSECT and EXCEPT compare whole rows, so two NULL values count as equal. This differs from the = comparison, where NULL = NULL is unknown and never true. A NULL email present in both tables therefore appears once in the INTERSECT result.
Exercise
Write a query that returns emails found in customers but not in unsubscribed.
Show answer
SELECT email FROM customers EXCEPT SELECT email FROM unsubscribed;