SQL COUNT DISTINCT

Counts unique values only — repeats collapse down to one before counting.

What & Why

COUNT(DISTINCT column) counts how many different values appear — duplicates get counted once, no matter how many times they repeat.

See How It Works

BUSINESS QUESTION

How many distinct channels are represented?

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 duplicate channels collapseRow 1 of 4
COUNT(DISTINCT channel)
rowcampaignchannelspenddistinct
1Spring Launchgoogle_ads55,000+1
2Retention Webinaremail45,000WAIT
3Finance Retargetinglinkedin50,000WAIT
4Enterprise Searchgoogle_ads60,000WAIT
Running resultCOUNT(DISTINCT channel) = 1

google_ads appears for the first time, so the distinct count becomes 1.

EXAMPLE QUERY
SELECT COUNT(DISTINCT channel) AS distinct_channels
FROM marketing.campaigns;
Now You Try

Practice this concept

Marketing wants the number of unique lead sources and unique countries represented in the lead pipeline.

Available schema
marketing

Prefix tables with marketing.table_name.

unique_sourcesunique_countries
marketing.leads
ColumnType
idinteger
campaign_idinteger
emailtext
created_attimestamp with time zone
qualified_attimestamp with time zone
converted_attimestamp with time zone
lead_scoreinteger
sourcetext
countrytext
archive_statustext
query.sql
Beginner business practice

Sign up free to try it on a real business scenario