Chapter 16 · Lesson 3 of 4

Extracting Parts of a String

Pull pieces out of text with LENGTH, LEFT, RIGHT, SUBSTRING, STRPOS, and SPLIT_PART, such as extracting the domain from every email address.

Often you need only part of a text value. DuckDB has functions for the common cases:

• LENGTH(text) counts characters. • LEFT(text, n) and RIGHT(text, n) take characters from either end. • SUBSTRING(text, start, length) takes characters from the middle. Positions start at 1. • STRPOS(text, search) returns the position of a substring, or 0 when it is missing. • SPLIT_PART(text, separator, n) splits text on a separator and returns the n-th part.

SELECT
  email,
  STRPOS(email, '@') AS at_position,
  SPLIT_PART(email, '@', 1) AS mailbox,
  SPLIT_PART(email, '@', 2) AS domain
FROM contacts_raw

SPLIT_PART is usually the clearest choice when a value has a clear separator, like the @ in an email or the - in a product code. Clean the value first with TRIM and LOWER so the extracted parts are consistent.

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 email_domain: the part after '@', trimmed and lowercase (for example 'example.com'). Order by id.

Hint: SPLIT_PART(LOWER(TRIM(email)), '@', 2) AS email_domain

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