SQL SUBSTRING

Extracts a specific slice of a string, given a starting position and (optionally) a length — the general-purpose text-slicing tool.

What & Why

SUBSTRING(text FROM start FOR length) pulls out a piece of a string, starting at a given position (1-indexed, not 0-indexed) and running for a given number of characters. Omitting FOR length takes everything from the start position to the end of the string.

See How It Works

BUSINESS QUESTION

Marketing wants three SUBSTRING slices beside every lead email: a fixed prefix, the domain, and the complete email name.

idcampaign_idemailcreated_atqualified_atconverted_atlead_scoresourcecountry
3011ana@example.com2024-01-21 09:10:00+002024-01-22 11:00:00+002024-02-02 10:00:00+0086google_adsUS
3021ben@example.com2024-01-24 12:40:00+00NULLNULL52google_adsCA
3032chloe@example.com2024-02-16 08:30:00+002024-02-18 14:20:00+00NULL74emailGB
3043dev@example.com2024-03-20 17:15:00+002024-03-21 09:00:00+002024-04-04 16:00:00+0091linkedinUS
Watch the same emails produce three different slicesStep 1 of 3
SUBSTRING(email FROM 1 FOR 4)
idemailemail_prefix
301ana@example.comana@
302ben@example.comben@
303chloe@example.comchlo
304dev@example.comdev@

A fixed start and length return the first four characters from each real lead email.

EXAMPLE QUERY
SELECT
  id,
  email,
  SUBSTRING(email FROM 1 FOR 4) AS email_prefix,
  SUBSTRING(email FROM POSITION('@' IN email) + 1) AS email_domain,
  SUBSTRING(email FROM 1 FOR POSITION('@' IN email) - 1) AS email_name
FROM marketing.leads
WHERE POSITION('@' IN email) > 0
ORDER BY id;
Now You Try

Practice this concept

Marketing wants three SUBSTRING slice forms beside every lead email.

Available schema
marketing

Prefix tables with marketing.table_name.

idemailemail_prefixemail_domainemail_name
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
Intermediate business practice

Sign up free to try it on a real business scenario