How to include quotes in comma separated column with MySQL?


Let us first create a −

mysql> create table DemoTable1407
   -> (
   -> Name text
   -> );
Query OK, 0 rows affected (0.51 sec)

Insert some records in the table using insert −

mysql> insert into DemoTable1407 values('John,Bob');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable1407 values('Carol,David,Adam');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1407 values('Mike,Sam,Chris');
Query OK, 1 row affected (0.19 sec)

Display all records from the table using select −

mysql> select * from DemoTable1407;

This will produce the following output −

+------------------+
| Name             |
+------------------+
| John,Bob         |
| Carol,David,Adam |
| Mike,Sam,Chris   |
+------------------+
3 rows in set (0.00 sec)

Here is the query to include quotes in comma separated column with MySQL −

mysql> select concat("'", replace(Name, ",", "','"), "'") AS IncludingQuotes from DemoTable1407;

This will produce the following output −

+------------------------+
| IncludingQuotes        |
+------------------------+
| 'John','Bob'           |
| 'Carol','David','Adam' |
| 'Mike','Sam','Chris'   |
+------------------------+
3 rows in set (0.00 sec)

Updated on: 11-Nov-2019

682 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements