New line separator doesn't work for group_concat function in MySQL? How to use it correctly?


To use new line separator in group_concat() function, follow the below syntax −

select group_concat(concat_ws(' ',yourColumnName1, yourColumnName2) SEPARATOR "\r
") from yourTableName;

Let us first create a table −

mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   FirstName varchar(20),
   LastName varchar(20)
   );
Query OK, 0 rows affected (0.67 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(FirstName,LastName) values('John','Smith');
Query OK, 1 row affected (0.10 sec)

mysql> insert into DemoTable(FirstName,LastName) values('David','Miller');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable(FirstName,LastName) values('John','Doe');
Query OK, 1 row affected (0.13 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+-----------+----------+
| Id | FirstName | LastName |
+----+-----------+----------+
| 1  | John      | Smith    |
| 2  | David     | Miller   |
| 3  | John      | Doe      |
+----+-----------+----------+
3 rows in set (0.00 sec)

Following is the query to work with new line separator for group_concat function −

mysql> select group_concat(concat_ws(' ',FirstName, LastName) SEPARATOR "\r
") from DemoTable;

This will produce the following output &mnus;

+-------------------------------------------------------------------+
| group_concat(concat_ws(' ',FirstName, LastName) SEPARATOR "\r
") | +-------------------------------------------------------------------+ | John Smith David Miller John Doe                                 | +-------------------------------------------------------------------+ 1 row in set (0.00 sec)

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements