Skip to main content
Albero Academy

String & Text Functions

Clean and transform text in queries — concatenation, case, trimming, substrings, replacement, and search.

Chapter 10SQL13 min readBeginner friendly
  • #SQL
  • #Strings
  • #Functions

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

joining & casing
SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM students;
SELECT first_name || ' ' || last_name AS full_name FROM students; -- || in Postgres/SQLite
SELECT UPPER(name), LOWER(email) FROM students;
SELECT INITCAP('aanya kapoor'); -- 'Aanya Kapoor' (Postgres)

Trimming & length

whitespace & size
SELECT TRIM(' Albero '); -- 'Albero' (also LTRIM / RTRIM)
SELECT LENGTH(name); -- number of characters
SELECT LPAD(id::text, 5, '0'); -- '00042' (pad to width)

Substrings & position

extracting parts
SELECT SUBSTRING(email FROM 1 FOR 5); -- first 5 characters
SELECT LEFT(name, 3), RIGHT(phone, 4); -- first 3 / last 4
SELECT POSITION('@' IN email); -- index of the @
-- The domain from an email:
SELECT SUBSTRING(email FROM POSITION('@' IN email) + 1) AS domain;

Replace & clean

cleaning data
SELECT REPLACE(phone, '-', ''); -- strip dashes
SELECT 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

  1. 01Concatenate with CONCAT() or ||; change case with UPPER/LOWER/INITCAP.
  2. 02Clean whitespace with TRIM/LTRIM/RTRIM; measure with LENGTH; pad with LPAD/RPAD.
  3. 03Extract with SUBSTRING, LEFT/RIGHT and POSITION to locate a character.
  4. 04REPLACE swaps text; chain functions to normalise (trim + lower + replace).
  5. 05Normalise text on insert so downstream joins and filters stay reliable.