Chapter 16 · Lesson 1 of 4
Changing Case and Trimming Spaces
Normalize messy text with LOWER, UPPER, and TRIM so values that look the same really compare as equal, such as emails with stray capitals and spaces.
Text exported from forms, spreadsheets, and other systems is rarely tidy. Two values can look the same to a person and still be different to SQL:
SELECT '[email protected] ' = '[email protected]' AS same
-- falseThree functions fix most of these problems:
• LOWER(text) and UPPER(text) change letter case.
• TRIM(text) removes spaces at the start and end. LTRIM and RTRIM trim only one side.
Functions can be nested. The inner one runs first:
SELECT id, email, LOWER(TRIM(email)) AS clean_email
FROM contacts_rawMost string functions, including LOWER, UPPER, and TRIM, return NULL when their input is NULL, so a missing email stays missing. Filter those rows with WHERE email IS NOT NULL when you only want real values.
Sample data
This lesson loads the contacts_raw table (5 rows of messy contact data) into DuckDB in your browser with one click, so you can run every example without uploading anything.
Setup SQL for contacts_raw
CREATE OR REPLACE TABLE contacts_raw (
id INTEGER,
full_name VARCHAR,
email VARCHAR,
phone VARCHAR,
city VARCHAR
);
INSERT INTO contacts_raw VALUES
(1, ' alice JOHNSON ', '[email protected]', '+1 (555) 010-1234', 'new york'),
(2, 'Bob Lee', '[email protected] ', '555.010.5678', 'Boston '),
(3, 'Carla Diaz', '[email protected]', '+49 30 1234567', 'berlin'),
(4, 'Dev Patel', ' [email protected]', NULL, ' Mumbai'),
(5, 'Emma Stone', NULL, '555-010-9999', 'new york');Practice challenge
For contacts that have an email, return id and clean_email: the email with surrounding spaces removed and converted to lowercase. Order by id.
Hint: LOWER(TRIM(email)) AS clean_email ... WHERE email IS NOT NULL ORDER BY id
Run your query in the editor and the lesson checks the result automatically.
Lessons in String Functions
Clean and reshape text with SQL string functions: change case, trim spaces, concatenate values, extract parts of strings, and replace patterns with regular expressions.
Related guides
SQL String Functions for Cleaning Text: TRIM, LOWER, SPLIT_PART, and REGEXP_REPLACE
Exported text is messy. A handful of SQL string functions fix most of it: trim and lowercase values, join fields safely, split out parts, and strip characters with regex.
SQL Cheat Sheet for Data Analysis: Filter, Group, Join, Dates, and Ranking
One pattern per common analysis question, from previewing a new table to ranking rows inside groups, each linked to a lesson where you can practice it.