Combine strings

2 snippets in SQL

SQLSQL

STRING_AGG / GROUP_CONCAT

SQL · Aggregation
Syntax
-- PostgreSQL / ANSI
STRING_AGG(column, delimiter)
-- MySQL
GROUP_CONCAT(column SEPARATOR delimiter)
Example
-- PostgreSQL
SELECT
  order_id,
  STRING_AGG(product_name, ', ' ORDER BY product_name) AS products
FROM order_items oi
JOIN products p ON p.id = oi.product_id
GROUP BY order_id;
Output
-- order_id | products
-- 101      | Keyboard, Monitor, Mouse

Note STRING_AGG is standard SQL. MySQL uses GROUP_CONCAT with a default max length of 1024 characters - increase group_concat_max_len if results get truncated.

CONCAT / String Concatenation

SQL · String Functions
Syntax
CONCAT(str1, str2, ...)
-- or ANSI: str1 || str2
Example
SELECT
  CONCAT(first_name, ' ', last_name) AS full_name,
  first_name || ' ' || last_name AS full_name_ansi
FROM users;
Output
-- full_name     | full_name_ansi
-- Alice Johnson | Alice Johnson

Note The || operator is ANSI standard and works in PostgreSQL. MySQL uses CONCAT() only. In MySQL, CONCAT returns NULL if any argument is NULL. In PostgreSQL, || with a NULL also returns NULL. Use COALESCE to handle NULLs.

Frequently asked questions

How do you combine strings?
SQL covers this with 2 copy-ready snippets on this page. The "STRING_AGG / GROUP_CONCAT" snippet in SQL uses `-- PostgreSQL / ANSI`.
Which statement does the SQL example use?
The "STRING_AGG / GROUP_CONCAT" snippet uses `-- PostgreSQL / ANSI`, from the Aggregation section of the SQL cheat sheet.
What other SQL snippets are shown for "combine strings"?
Besides "STRING_AGG / GROUP_CONCAT", this page also shows "CONCAT / String Concatenation".
Is there anything to watch out for?
Yes. For "STRING_AGG / GROUP_CONCAT": STRING_AGG is standard SQL. MySQL uses GROUP_CONCAT with a default max length of 1024 characters - increase group_concat_max_len if results get truncated.