SQL String Functions

Real text data is messy — inconsistent case, stray whitespace, values crammed together that should be separate. This series covers reading, cleaning, combining, and extracting pieces of text.

What & Why

Numbers and dates tend to arrive already well-formed. Text almost never does — names typed in all caps, emails with extra spaces, phone numbers formatted five different ways. This series covers the toolkit for combining text (CONCAT, ||), cleaning it (TRIM, UPPER/LOWER/INITCAP), measuring and slicing it (LENGTH, SUBSTRING, LEFT/RIGHT), finding and replacing pieces (POSITION, REPLACE, SPLIT_PART), and aggregating it across rows (STRING_AGG).

See How It Works

BUSINESS QUESTION

Marketing standardizes lead sources before counting them.

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
EXAMPLE QUERY
SELECT
  LOWER(TRIM(source)) AS normalized_source,
  COUNT(*) AS leads
FROM marketing.leads
GROUP BY 1
ORDER BY leads DESC, normalized_source ASC;
RESULT — exact output from the displayed Queryflo rows
normalized_sourceleads
google_ads2
email1
linkedin1

LOWER and TRIM preserve the three actual lead-source groups.

Now You Try

Practice this concept

Marketing wants normalized lead sources with their lead counts, ordered by lead count descending and normalized source ascending.

Available schema
marketing

Prefix tables with marketing.table_name.

normalized_sourceleads
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