Sub topic 3
Joining strings with ||, concat and concat_ws
PostgreSQL gives you three ways to join strings: the || operator, the concat function, and the concat_ws function. They give the same result when every input has a value, and different results when an input is NULL. This chapter assumes you can write basic SELECT queries, you know that NULL means "unknown" rather than "empty", and you can run queries in psql or another client.
The || operator
|| joins two values and returns the result as text.
SELECT 'Post' || 'gre' || 'SQL' AS name;This returns PostgreSQLs-style output only if you type it that way. Here it returns PostgreSQL.
|| is strict. If either operand is NULL, the whole result is NULL:
SELECT 'a' || NULL AS with_operator;The result is NULL, not a. Chain several || and a single NULL anywhere erases the entire result. This is the most common source of "my column came back empty" bugs in report queries.
Mixing types
|| accepts a text value on one side and a non-array value of almost any type on the other. PostgreSQL converts the other value to text:
SELECT 'Order #' || 42 AS label,
'Shipped on ' || DATE '2026-11-27' AS shipped;Both operands cannot be non-text, though. SELECT 1 || 2 fails with operator does not exist: integer || integer. Cast one side: 1::text || 2.
Precedence
|| belongs to the "any other operator" group. That group binds more loosely than + and -. So this query does arithmetic first:
SELECT 'Total: ' || 1 + 2 AS total;It returns Total: 3, because 1 + 2 is evaluated before the join. When you mix || with arithmetic or comparisons, add parentheses so the reader does not have to remember the precedence table.
concat
concat takes any number of arguments of any type and joins their text forms. Unlike ||, it treats NULL as if the argument were not there:
SELECT concat('a', NULL, 'b') AS result;The result is ab. If every argument is NULL, the result is an empty string, not NULL:
SELECT concat(NULL, NULL) IS NULL AS is_null,
concat(NULL, NULL) = '' AS is_empty;Both columns return f and t respectively: is_null is false, is_empty is true.
Because concat accepts "any" type, you do not need casts: concat('Order #', 42) returns Order #42.
concat_ws
concat_ws means "concatenate with separator". The first argument is the separator. The rest are the values to join:
SELECT concat_ws(', ', 'x', NULL, 'z') AS result;The result is x, z. NULL arguments are skipped, and no separator is added for them. This is the function you want for building lists such as addresses or names, where some parts may be missing.
Rules to remember:
- If the separator is NULL, the result is NULL.
- If every value is NULL, the result is an empty string.
- Empty strings are not NULL.
concat_ws(',', 'a', '', 'b')returnsa,,b.
You can pass an array with VARIADIC:
SELECT concat_ws('-', VARIADIC ARRAY['2026', '11', '27']) AS iso_date;This returns 2026-11-27.
Comparing the three on real rows
The next script creates a temporary table with a missing middle name (NULL) and an empty one (''), then builds a full name four ways.
CREATE TEMP TABLE people (
id int,
first_name text,
middle_name text,
last_name text
);
INSERT INTO people VALUES
(1, 'Ada', NULL, 'Lovelace'),
(2, 'Grace', 'Brewster', 'Hopper'),
(3, 'Alan', '', 'Turing');
SELECT id,
first_name || ' ' || middle_name || ' ' || last_name AS with_operator,
concat(first_name, ' ', middle_name, ' ', last_name) AS with_concat,
concat_ws(' ', first_name, middle_name, last_name) AS with_ws,
concat_ws(' ', first_name, NULLIF(middle_name, ''), last_name) AS clean
FROM people
ORDER BY id;| id | with_operator | with_concat | with_ws | clean |
|---|---|---|---|---|
| 1 | NULL | `Ada Lovelace` (two spaces) | `Ada Lovelace` | `Ada Lovelace` |
| 2 | `Grace Brewster Hopper` | `Grace Brewster Hopper` | `Grace Brewster Hopper` | `Grace Brewster Hopper` |
| 3 | `Alan Turing` (two spaces) | `Alan Turing` (two spaces) | `Alan Turing` (two spaces) | `Alan Turing` |
Three things stand out:
||loses the whole row 1 value because of one NULL.concatkeeps row 1, but the literal' 'separators stay, so you get a double space.concat_wshandles NULL correctly, but still treats''as a real value. Wrapping the column inNULLIF(middle_name, '')turns empty strings into NULL so they are skipped too.
Choosing between them
A few more decision points:
- Use
||when you want NULL to propagate. For example, a label that should be NULL when the data is incomplete is easier to detect with||. - Use
coalesce(col, 'n/a')to replace NULL with a visible default while keeping||. - Use
concat_wsfor names, addresses, tags and CSV-style lines.
Gotchas and edge cases
concat and concat_ws are not immutable
|| is backed by an immutable function. concat and concat_ws are only STABLE, because converting arbitrary types to text can depend on settings such as DateStyle. PostgreSQL refuses to use stable functions in an index expression:
CREATE INDEX idx_people_name ON people (concat_ws(' ', first_name, last_name));This fails with functions in index expression must be marked IMMUTABLE. If you need an index on a joined value, build the expression from || and coalesce over text columns:
CREATE INDEX idx_people_name
ON people ((first_name || ' ' || coalesce(last_name, '')));Queries must repeat the same expression to use that index.
char(n) padding
When a char(n) value is cast to text, trailing spaces are removed. || performs that cast, but concat converts through the type's output function and keeps the padding:
SELECT length('ab'::char(5) || 'x') AS with_operator,
length(concat('ab'::char(5), 'x')) AS with_concat;This returns 3 and 6. Prefer text columns, as covered in the chapter on character types, and this difference stops mattering.
Performance and size
Joining is cheap per row, but each result is a new value. Repeatedly joining inside a loop or a recursive query builds many temporary strings. For combining many rows into one string, use string_agg, which is covered in a later chapter. A single value of text cannot exceed about 1 GB.
Joining non-text types
concat converts values with their text output, so booleans appear as t and f, and timestamps follow the session's DateStyle. If you need a specific format, call to_char or cast explicitly before joining.
Summary of behaviors
| Expression | Any NULL input | All NULL | Separator support | Column | Column |
|---|---|---|---|---|---|
| `a \ | \ | b` | Result is NULL | NULL | No |
| `concat(a, b)` | NULL skipped | Empty string | No | ||
| `concat_ws(sep, a, b)` | NULL skipped, no extra separator | Empty string | Yes (NULL separator gives NULL) |
Exercise
Given a table addresses(street text, unit text, city text, postcode text), where unit is NULL for houses and sometimes '' for imported rows, write a query that returns one line such as 12 Main St, Springfield, 12345 or 12 Main St, Apt 4, Springfield, 12345, with no doubled commas.
Show answer
SELECT concatws(', ', street, NULLIF(unit, ''), city, postcode) AS address FROM addresses; NULLIF turns empty units into NULL, and concatws skips NULL values without adding a separator.
Exercise
What do SELECT 'a' || NULL || 'b', SELECT concat('a', NULL, 'b') and SELECT concat_ws(NULL, 'a', 'b') return?
Show answer
The first returns NULL because || propagates NULL. The second returns ab because concat skips NULL. The third returns NULL because a NULL separator makes concat_ws return NULL.
Exercise
Why does CREATE INDEX ON people (concat_ws(' ', first_name, last_name)) fail, and what can you use instead?
Show answer
concatws is only STABLE, and index expressions require IMMUTABLE functions. Use an expression built from || and coalesce, such as `(firstname || ' ' || coalesce(last_name, ''))`, and repeat the same expression in queries.