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
Marketing standardizes lead sources before counting them.
| id | campaign_id | created_at | qualified_at | converted_at | lead_score | source | country | |
|---|---|---|---|---|---|---|---|---|
| 301 | 1 | ana@example.com | 2024-01-21 09:10:00+00 | 2024-01-22 11:00:00+00 | 2024-02-02 10:00:00+00 | 86 | google_ads | US |
| 302 | 1 | ben@example.com | 2024-01-24 12:40:00+00 | NULL | NULL | 52 | google_ads | CA |
| 303 | 2 | chloe@example.com | 2024-02-16 08:30:00+00 | 2024-02-18 14:20:00+00 | NULL | 74 | GB | |
| 304 | 3 | dev@example.com | 2024-03-20 17:15:00+00 | 2024-03-21 09:00:00+00 | 2024-04-04 16:00:00+00 | 91 | US |
SELECT
LOWER(TRIM(source)) AS normalized_source,
COUNT(*) AS leads
FROM marketing.leads
GROUP BY 1
ORDER BY leads DESC, normalized_source ASC;| normalized_source | leads |
|---|---|
| google_ads | 2 |
| 1 | |
| 1 |
LOWER and TRIM preserve the three actual lead-source groups.
Practice this concept
Marketing wants normalized lead sources with their lead counts, ordered by lead count descending and normalized source ascending.
marketingPrefix tables with marketing.table_name.
normalized_sourceleadsmarketing.leads| Column | Type |
|---|---|
| id | integer |
| campaign_id | integer |
| text | |
| created_at | timestamp with time zone |
| qualified_at | timestamp with time zone |
| converted_at | timestamp with time zone |
| lead_score | integer |
| source | text |
| country | text |
| archive_status | text |
Sign up free to try it on a real business scenario