String Functions (CONCAT, SUBSTRING, TRIM, UPPER, LOWER, REPLACE)
Clean and reshape text fields with everyday string functions.
In plain words
String functions tidy up text: cut off extra spaces, make letters the same case, swap bits, or take a piece out.
Think of it like…
Tidying a pile of handwritten name cards before filing them: trim the edges, write every name the same way, fix common misspellings, and only then sort them.
Where you’ve seen it
Cleaning city names before grouping: SELECT INITCAP(LOWER(TRIM(city))) AS city, COUNT(*) FROM customers GROUP BY 1; turns 'pune ', 'PUNE' and 'Pune' into one 'Pune' group.
Words you’ll hear
- TRIM / LTRIM / RTRIM
- Remove spaces (or given characters) from both ends, the left or the right.
- SUBSTRING(s FROM start FOR len)
- Part of a string; positions start at 1.
- CONCAT vs ||
- Both join strings; they differ in how they handle NULL.
- LENGTH vs CHAR_LENGTH
- In MySQL, LENGTH counts bytes and CHAR_LENGTH counts characters.
Visual diagram
Theory & example queries
The everyday functions
TRIM(s) removes leading and trailing spaces; TRIM(BOTH 'x' FROM s) removes a specific character. UPPER, LOWER and (in PostgreSQL and Oracle) INITCAP normalise case. REPLACE(s, 'from', 'to') swaps every occurrence. SUBSTRING(s FROM 1 FOR 3), LEFT(s, 3) and RIGHT(s, 4) take pieces, such as the last four digits of a phone number.
POSITION('@' IN email) (or STRPOS in PostgreSQL) finds where a substring starts, which combines with SUBSTRING to split values: the domain of an email is SUBSTRING(email FROM POSITION('@' IN email) + 1). LPAD and RPAD pad to a fixed width, such as zero-padding invoice numbers.
| id | country | city | signup_date |
|---|---|---|---|
| 1 | IN | Pune | 2026-10-01 |
| 2 | IN | Delhi | 2026-10-02 |
| 3 | NULL | Mumbai | 2026-10-03 |
SELECT LOWER( SUBSTRING( email FROM POSITION('@' IN email) + 1 ) ) AS domain, COUNT(*)FROM usersGROUP BY 1ORDER BY 2 DESC;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Users grouped by email domain3 sample rows
| domain | count |
|---|---|
| example.com | 24 |
| gmail.com | 17 |
| company.test | 6 |
Note: Counts and domains are illustrative; only the domain portion after the last @ is grouped after lowercasing.
Key takeaway: TRIM + LOWER first, then SUBSTRING / REPLACE for structure.
NULLs, bytes and case-insensitive matching
NULL handling differs. In PostgreSQL, first_name || ' ' || last_name is NULL if either part is NULL, while CONCAT() treats NULL as empty. In MySQL, CONCAT() returns NULL if any argument is NULL; CONCAT_WS(' ', first, last) skips NULLs. In MySQL, LENGTH counts bytes, so 'ñ' has length 2, while CHAR_LENGTH counts characters.
Case-insensitive comparison depends on collation: MySQL's default collations ignore case, PostgreSQL's don't. In PostgreSQL, compare LOWER(email) = LOWER($1) with an expression index on LOWER(email), or use the citext type. For data quality, clean values when they're written (and enforce it with a CHECK or a generated column) rather than in every query.
PostgreSQL: CONCAT_WS(' ', first_name, middle_name, last_name) skips NULL parts, so a missing middle name doesn't produce NULL or a double space.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Inspect the mess
Look at distinct values and their lengths to spot spaces, case variations and stray characters.
SELECT city, LENGTH(city), COUNT(*)FROM customersGROUP BY 1, 2When to use it & trade-offs
What it is
String functions clean and reshape text. TRIM removes surrounding spaces, UPPER/LOWER change case, REPLACE swaps substrings, SUBSTRING (or SUBSTR) takes part of a string (positions start at 1), CONCAT or || joins strings, and LENGTH or CHAR_LENGTH measures them. They're how imported, messy data becomes something you can group, join and compare.
Why it matters: Real data has trailing spaces, inconsistent capitalisation and stray characters, so "Pune", "pune " and "PUNE" become three different cities in a report. Knowing the functions, and their NULL and dialect quirks, is basic for any analyst or backend role.
When to reach for it
- Cleaning imported CSVs and form data
- Building display names and labels
- Extracting parts of identifiers, emails and codes
When to avoid or be careful
- Grouping or joining on raw, uncleaned text
- Using || in PostgreSQL when any part can be NULL
- Applying LOWER() to an indexed column in WHERE without an expression index
Cleaning in queries vs on write vs generated columns
Strengths: No schema changes.
Watch out: Repeated everywhere; functions on columns prevent index use.
Strengths: Every query sees clean data; indexes work.
Watch out: Needs a one-time cleanup of existing rows.
Strengths: Original value preserved; normalised version indexed.
Watch out: Extra storage and slightly more complex schema.
Interview signals & numbers to know
When this topic comes up
- “The same city appears three times in the report”
- “Extract the domain from the email”
- Trailing spaces in data
- Case-insensitive search
- Names coming out as NULL
Benchmarks & rules of thumb
- 1
- first position in SQL strings (not 0)
- NULL
- result of 'a' || NULL in PostgreSQL
- 2
- MySQL LENGTH of 'ñ' (bytes)
Common mistakes & follow-ups
Common interview mistakes
- Concatenating first and last names with || and getting NULL for everyone without a last name.
- Using 0-based positions with SUBSTRING and cutting off the first character.
- Comparing emails without LOWER/TRIM and creating duplicate accounts.
Likely interviewer follow-ups
- How would you find customers whose names differ only by case or spaces?
- What's the difference between CONCAT and || when a value is NULL?
- How would you make case-insensitive email lookups fast in PostgreSQL?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply String Functions (CONCAT, SUBSTRING, TRIM, UPPER, LOWER, REPLACE) with hands-on SQL practice and interview Q&A.