MySQL concatenation operator?

MySQLMySQLi Database

You can use in-built function CONCAT() from MySQL. The syntax is as follows −

SELECT CONCAT(('(',yourColumnName1,',', yourColumnName2,',',yourColumnName3,...N')')as anyVariableName from yourTableName;

To understand the above syntax, let us first create a table. The query to create a table is as follows −

mysql> create table Concatenation_OperatorDemo
-> (
->
-> VendorId int,
-> VendorName varchar(100),
-> VendorCountry varchar(100)
-> );
Query OK, 0 rows affected (0.69 sec)

Insert some records in the table using insert command. The query is as follows −

mysql> insert into Concatenation_OperatorDemo values(101,'Carol','US');
Query OK, 1 row affected (0.19 sec)

mysql> insert into Concatenation_OperatorDemo values(102,'Bob','UK');
Query OK, 1 row affected (0.18 sec)

mysql> insert into Concatenation_OperatorDemo values(103,'John','US');
Query OK, 1 row affected (0.14 sec)

mysql> insert into Concatenation_OperatorDemo values(104,'David','UK');
Query OK, 1 row affected (0.25 sec)

Display all records from the table using select statement. The query is as follows −

mysql> select *from Concatenation_OperatorDemo;

The following is the output −

+----------+------------+---------------+
| VendorId | VendorName | VendorCountry |
+----------+------------+---------------+
| 101      | Carol      | US            |
| 102      | Bob        | UK            |
| 103      | John       | US            |
| 104      | David      | UK            |
+----------+------------+---------------+
4 rows in set (0.00 sec)

Now you can concat N number of columns using concat() function. Here, we will concat all three columns from the above table. The query to concat the column values are as follows −

mysql> select concat('(',VendorId,',', VendorName,',', VendorCountry,')')as
ConcatenationDemo
-> from Concatenation_OperatorDemo;

The following is the output −

+-------------------+
| ConcatenationDemo |
+-------------------+
| (101,Carol,US)    |
| (102,Bob,UK)      |
| (103,John,US)     |
| (104,David,UK)    |
+-------------------+
4 rows in set (0.00 sec)
raja
Published on 11-Jan-2019 06:02:16
Advertisements