Real text data is messy — extra spaces, inconsistent case, values glued together. SQL's string functions let you clean and reshape text right in the query. Exact function names vary a little between databases, but the concepts are universal.
Concatenation & case
SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM students;SELECT first_name || ' ' || last_name AS full_name FROM students; -- || in Postgres/SQLiteSELECT UPPER(name), LOWER(email) FROM students;SELECT INITCAP('aanya kapoor'); -- 'Aanya Kapoor' (Postgres)
Trimming & length
SELECT TRIM(' Albero '); -- 'Albero' (also LTRIM / RTRIM)SELECT LENGTH(name); -- number of charactersSELECT LPAD(id::text, 5, '0'); -- '00042' (pad to width)
Substrings & position
SELECT SUBSTRING(email FROM 1 FOR 5); -- first 5 charactersSELECT LEFT(name, 3), RIGHT(phone, 4); -- first 3 / last 4SELECT POSITION('@' IN email); -- index of the @-- The domain from an email:SELECT SUBSTRING(email FROM POSITION('@' IN email) + 1) AS domain;
Replace & clean
SELECT REPLACE(phone, '-', ''); -- strip dashesSELECT REPLACE(TRIM(LOWER(email)), ' ', ''); -- chain to normalise-- Split-style extraction with SPLIT_PART (Postgres)SELECT SPLIT_PART(email, '@', 2) AS domain;
Practice
Build a full_name from first and last name. Normalise emails to trimmed lowercase. Extract the domain from an email using POSITION + SUBSTRING (or SPLIT_PART), and pad a numeric id to five digits with leading zeros.
Key takeaways
- 01Concatenate with CONCAT() or ||; change case with UPPER/LOWER/INITCAP.
- 02Clean whitespace with TRIM/LTRIM/RTRIM; measure with LENGTH; pad with LPAD/RPAD.
- 03Extract with SUBSTRING, LEFT/RIGHT and POSITION to locate a character.
- 04REPLACE swaps text; chain functions to normalise (trim + lower + replace).
- 05Normalise text on insert so downstream joins and filters stay reliable.
