SQL REPLACE

Swaps every occurrence of one substring for another — a straightforward find-and-replace, applied to every match in the string at once.

What & Why

REPLACE(text, from_str, to_str) replaces every occurrence of from_str with to_str. Every match gets replaced, not just the first one.

See How It Works

BUSINESS QUESTION

Marketing wants campaign names shown both with underscores and with spaces deleted so the two REPLACE behaviors are visible.

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 REPLACE substitute and delete exact textStep 1 of 2
REPLACE(LOWER(name), ' ', '_')
idnamecampaign_key
1Spring Launchspring_launch
2Retention Webinarretention_webinar
3Finance Retargetingfinance_retargeting
4Enterprise Searchenterprise_search

Every exact space is replaced with an underscore in the export key.

EXAMPLE QUERY
SELECT
  id,
  name,
  REPLACE(LOWER(name), ' ', '_') AS campaign_key,
  REPLACE(LOWER(name), ' ', '') AS compact_key
FROM marketing.campaigns
ORDER BY id;
Now You Try

Practice this concept

Marketing wants campaign-name spaces both replaced and deleted for two export keys.

Available schema
marketing

Prefix tables with marketing.table_name.

idnamecampaign_keycompact_key
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