Chapter 16 · Lesson 4 of 4

Cleaning Text with REPLACE and REGEXP_REPLACE

Remove or swap characters with REPLACE, and use REGEXP_REPLACE with the global flag to strip every non-digit from phone numbers in one step.

REPLACE(text, search, replacement) swaps every occurrence of a fixed string:

SELECT phone, REPLACE(phone, '-', '') AS without_dashes
FROM contacts_raw

That works for one character at a time. Phone numbers, though, contain spaces, dots, dashes, parentheses, and plus signs. A regular expression describes all of them at once. [^0-9] means "any character that is not a digit":

SELECT phone, REGEXP_REPLACE(phone, '[^0-9]', '', 'g') AS phone_digits
FROM contacts_raw

The fourth argument, 'g', means global: replace every match. Without it, DuckDB replaces only the first match, which is an easy mistake to miss.

To test whether text matches a pattern without changing it, use REGEXP_MATCHES(text, pattern), which returns true or false.

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 a phone number, return id and phone_digits: the phone with every non-digit character removed. Order by id.

Hint: REGEXP_REPLACE(phone, '[^0-9]', '', 'g') AS phone_digits ... WHERE phone IS NOT NULL

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