Chapter 16 · Lesson 2 of 4
Concatenating Text
Join text values with the || operator, concat, and concat_ws, and learn how each one treats NULL so missing values do not wipe out the whole result.
To join text values, use the || operator:
SELECT id, TRIM(full_name) || ' from ' || TRIM(city) AS display_name
FROM contacts_raw|| has one sharp edge: if any part is NULL, the whole result is NULL.
SELECT 'Phone: ' || NULL
-- NULLDuckDB offers two functions that are friendlier to missing values:
• concat(a, b, ...) joins its arguments and skips NULL values.
• concat_ws(separator, a, b, ...) joins with a separator and also skips NULL values, so you do not get doubled separators.
SELECT id, concat_ws(' | ', TRIM(full_name), email, phone) AS contact_card
FROM contacts_rawUse || when every part is required, and concat_ws when some parts are optional.
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
Return id and display_name, built as the trimmed full_name, then ' from ', then the trimmed city (for example 'Bob Lee from Boston'). Order by id.
Hint: TRIM(full_name) || ' from ' || TRIM(city) AS display_name
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.