Learn SQL/Advanced/Interview Patterns/SQL Find Duplicate Rows

SQL Find Duplicate Rows

One of the most-asked interview questions — group by whatever defines a duplicate, keep only groups with more than one row.

What & Why

A duplicate is defined by whichever columns should have been unique. Group by those columns, count the rows in each group, and keep only groups where that count exceeds 1.

See How It Works

BUSINESS QUESTION

Find acquisition channels that appear on more than one campaign row.

idnamechannelspendstart_dateend_datestatustarget_segment
1Spring Launchgoogle_ads55000.002024-01-152024-03-31activesmb
2Retention Webinaremail45000.002024-02-102024-04-15activeenterprise
3Finance Retargetinglinkedin50000.002024-03-122024-05-31activeenterprise
4Enterprise Searchgoogle_ads60000.002024-04-012024-06-30activeenterprise
Watch GROUP BY reveal a repeated campaign channelStep 1 of 3
GROUP BY channel HAVING COUNT(*) > 1
campaign_idnamechannel
1Spring Launchgoogle_ads
2Retention Webinaremail
3Finance Retargetinglinkedin
4Enterprise Searchgoogle_ads

Start from the four real marketing.campaigns rows.

EXAMPLE QUERY
SELECT
  channel,
  COUNT(*) AS occurrences,
  MIN(start_date) AS first_seen_at,
  MAX(start_date) AS last_seen_at
FROM marketing.campaigns
GROUP BY channel
HAVING COUNT(*) > 1
ORDER BY occurrences DESC, channel;

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario