Store strings in variables and concatenate them to display them in a single column in MYSQL


For this, use CONCAT_WS() in MySQL. Let us first create a −

mysql> create table DemoTable1433
   -> (
   -> ClientId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> ClientFirstName varchar(20),
   -> ClientLastName varchar(20)
   -> );
Query OK, 0 rows affected (0.58 sec)

Insert some records in the table using insert −

mysql> insert into DemoTable1433(ClientFirstName,ClientLastName) values('David','Miller');
Query OK, 1 row affected (0.14 sec)

Display all records from the table using select −

mysql> select * from DemoTable1433;

This will produce the following output −

+----------+-----------------+----------------+
| ClientId | ClientFirstName | ClientLastName |
+----------+-----------------+----------------+
|        1 | David           | Miller         |
+----------+-----------------+----------------+
1 row in set (0.00 sec)

Following is the query to store strings in variables and concatenate them −

mysql> set @concat_variable:=(select concat_ws('-',ClientFirstName,ClientLastName) from DemoTable1433);
Query OK, 0 rows affected (0.00 sec)
mysql> select @concat_variable;

This will produce the following output −

+------------------+
| @concat_variable |
+------------------+
| David-Miller     |
+------------------+
1 row in set (0.00 sec)

Updated on: 12-Nov-2019

186 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements