capypad
0 day streak
sql / intermediate
Snippet

Set Intersection with INTERSECT

The INTERSECT operator returns only the distinct rows that are present in both the first and second query result sets. It is useful for finding common records across different datasets without using complex joins.

snippet.sql
sql
1
2
3
SELECT user_id FROM newsletter_subscribers
INTERSECT
SELECT user_id FROM premium_members;
Breakdown
1
SELECT user_id FROM newsletter_subscribers
Selects the IDs of all users who subscribed to the newsletter.
2
INTERSECT
Filters the results to keep only those IDs present in both queries.
3
SELECT user_id FROM premium_members
Selects the IDs of all premium members to compare with the first list.