SQL STRING_AGG

An aggregate function that combines TEXT values across multiple rows into one delimited string — the string-world counterpart to COUNT, SUM, and friends.

What & Why

STRING_AGG(column, delimiter) is an aggregate function — it works with GROUP BY exactly like SUM or COUNT do, but instead of computing a number across a group of rows, it concatenates a text column across them, joined by the given delimiter.

See How It Works

BUSINESS QUESTION

Marketing wants an alphabetized campaign list for every channel.

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
EXAMPLE QUERY
SELECT
  channel,
  STRING_AGG(name, ', ' ORDER BY name) AS campaigns
FROM marketing.campaigns
GROUP BY channel
ORDER BY channel;
RESULT — exact output from the displayed Queryflo rows
channelcampaigns
emailRetention Webinar
google_adsEnterprise Search, Spring Launch
linkedinFinance Retargeting

STRING_AGG alphabetizes campaign names inside each channel group.

Now You Try

Practice this concept

Marketing wants an alphabetized comma-separated campaign list for every channel.

Available schema
marketing

Prefix tables with marketing.table_name.

channelcampaigns
marketing.campaigns
ColumnType
idinteger
nametext
channeltext
spendnumeric
start_datedate
end_datedate
statustext
target_segmenttext
legacy_idtext
query.sql
Intermediate business practice

Sign up free to try it on a real business scenario