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
-- false

Three 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_raw

Most 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.

Open this lesson in the SQL editor

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.

  1. 01 · Changing Case and Trimming Spaces
  2. 02 · Concatenating Text
  3. 03 · Extracting Parts of a String
  4. 04 · Cleaning Text with REPLACE and REGEXP_REPLACE

Related guides