SQL REGEXP_REPLACE

REPLACE's more powerful sibling — matches a PATTERN instead of a fixed string, using regular expressions.

What & Why

REGEXP_REPLACE(text, pattern, replacement, flags) replaces text matching a regular expression pattern, rather than an exact literal string. This is the tool for problems REPLACE genuinely can't express — like "collapse any number of consecutive spaces into one," which has no single fixed substring to search for.

See How It Works

BUSINESS QUESTION

Marketing wants campaign names converted into lowercase hyphenated slugs.

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
  id AS campaign_id,
  name,
  LOWER(REGEXP_REPLACE(TRIM(name), '\s+', '-', 'g')) AS campaign_slug
FROM marketing.campaigns
ORDER BY campaign_id;
RESULT — exact output from the displayed Queryflo rows
campaign_idnamecampaign_slug
1Spring Launchspring-launch
2Retention Webinarretention-webinar
3Finance Retargetingfinance-retargeting
4Enterprise Searchenterprise-search

The regex replaces each real name's whitespace with a hyphen before LOWER.

Now You Try

Practice this concept

Marketing wants campaign names converted into lowercase slugs with every whitespace run replaced by one hyphen.

Available schema
marketing

Prefix tables with marketing.table_name.

campaign_idnamecampaign_slug
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