How to make MySQL display results in a single line?


For this, you can use group_concat(). Let us first create a table −

mysql> create table DemoTable1507
   -> (
   -> Name varchar(20),
   -> PaperSet int
   -> );
Query OK, 0 rows affected (0.68 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1507 values('Chris',111);
Query OK, 1 row affected (0.37 sec)
mysql> insert into DemoTable1507 values('David',112);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable1507 values('Mike',111);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable1507 values('Bob',113);
Query OK, 1 row affected (0.14 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1507;

This will produce the following output −

+-------+----------+
| Name  | PaperSet |
+-------+----------+
| Chris |      111 |
| David |      112 |
| Mike  |      111 |
| Bob   |      113 |
+-------+----------+
4 rows in set (0.00 sec)

Here is the query to make MySQL display results only in a single line −

mysql> select group_concat(Name order by Name desc separator ':')
   -> from DemoTable1507
   -> where PaperSet=111;

This will produce the following output −

+-----------------------------------------------------+
| group_concat(Name order by Name desc separator ':') |
+-----------------------------------------------------+
| Mike:Chris                                          |
+-----------------------------------------------------+
1 row in set (0.00 sec)

Updated on: 11-Dec-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements