Join ML Engineer Interview MasterClass (April Cohort) led by FAANG Data Scientists | Just 6 seats remaining...
ML Engineer MasterClass (April) | 6 seats left
By the end of this lesson, you will:
Your manager at Google Ads, Jordan, wants to compare different sets of advertisers and campaigns.
“Can you find advertisers who have run both Search and Display ads? Also, can we check which advertisers signed up but never launched a campaign?”
Your task is to use INTERSECT to find common advertisers and EXCEPT to identify advertisers without campaigns.
| Operator | What It Does | Removes Duplicates? | Use Case |
|---|---|---|---|
| INTERSECT | Returns rows that exist in both queries | ✅ Yes | Finding common records |
| EXCEPT | Returns rows from the first query that don’t exist in the second | ✅ Yes | Finding differences between two datasets |
SELECT column1 FROM table1
INTERSECT
SELECT column1 FROM table2;SELECT column1 FROM table1
EXCEPT
SELECT column1 FROM table2;Jordan wants to find advertisers who have run both Search and Display campaigns.
SELECT user_id FROM google_ads_campaigns WHERE ad_type = 'Search'
INTERSECT
SELECT user_id FROM google_ads_campaigns WHERE ad_type = 'Display';| user_id |
|---|
| 2 |
| 4 |
What’s Happening?
INTERSECT returns only advertisers who appear in both queries.Jordan also wants to see which advertisers have signed up but never launched a campaign.
SELECT user_id FROM google_ads_users
EXCEPT
SELECT DISTINCT user_id FROM google_ads_campaigns;| user_id |
|---|
| 3 |
What’s Happening?
EXCEPT removes advertisers who have campaigns, leaving only those without campaigns.| Scenario | Best Choice | Why? |
|---|---|---|
| Finding users present in both datasets | INTERSECT | Ensures only common results are kept |
| Identifying missing or excluded data | EXCEPT | Finds records in one dataset but not in another |
| Comparing lists of customers, transactions, or activity logs | Both | Depends on whether you want common or missing records |
Tip:
INTERSECT and EXCEPT remove duplicates, they can be slower on large datasets.UNION ALL or filtering (WHERE NOT IN) if performance is a concern.Jordan wants to list advertisers who have run both Search and Display campaigns.
Filter condition:
user_id in ascending order.| user_id |
|---|
| 2 |
| 4 |
Write an SQL query to return the requested data.
Jordan also wants to see which advertisers signed up but never launched a campaign.
Filter condition:
| user_id |
|---|
| 3 |
Write an SQL query to return the requested data.