Languages
[Edit]
EN

MySQL - concat column rows as single string using SELECT query

8 points
Created by:
Marcin
20600

In this short article, we would like to show how in MySQL, build a SELECT query that returns one string created from concated column rows.

Hint: below examples use built-in GROUP_CONCAT() function that joins indicated columns as a single string.

Quick solution:

SELECT GROUP_CONCAT(u.`name` SEPARATOR ' ')
FROM users u
WHERE u.`id` = 100

Result:

john matt ann

 

Returning column data as JavaScript array in JSON format:

SET @text:= (
	SELECT GROUP_CONCAT('"', t.name, '"')
	FROM users u
	WHERE u.`id` = 100
);

SELECT CONCAT('[', @text, ']');

Result:

["john","matt","ann"]

Note: GROUP_CONCAT() function uses coma as default separator. 

Alternative titles

  1. MySQL - join column rows as single string using SELECT query
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join