Concatenate two columns in MySQL?

MySQLMySQLi Database

To concatenate two columns, use CONCAT() function in MySQL. The syntax is as follows −

select CONCAT(yourColumnName1, ' ',yourColumnName2) as anyVariableName from yourTableName;

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

mysql> create table concatenateTwoColumnsDemo
   −> (
   −> StudentId int,
   −> StudentName varchar(200),
   −> StudentAge int
   −> );
Query OK, 0 rows affected (1.06 sec)

Now you can insert some records in the table. The query to insert records is as follows −

mysql> insert into concatenateTwoColumnsDemo values(1,'Sam',21);
Query OK, 1 row affected (0.18 sec)

mysql> insert into concatenateTwoColumnsDemo values(2,'David',24);
Query OK, 1 row affected (0.17 sec)

mysql> insert into concatenateTwoColumnsDemo values(3,'Carol',22);
Query OK, 1 row affected (0.13 sec)

mysql> insert into concatenateTwoColumnsDemo values(4,'Johnson',19);
Query OK, 1 row affected (0.17 sec)

Display all records from the table with the help of select statement. The query is as follows −

mysql> select *from concatenateTwoColumnsDemo;

The following is the output −

+-----------+-------------+------------+
| StudentId | StudentName | StudentAge |
+-----------+-------------+------------+
|         1 | Sam         |         21 |
|         2 | David       |         24 |
|         3 | Carol       |         22 |
|         4 | Johnson     |         19 |
+-----------+-------------+------------+
4 rows in set (0.00 sec)

Implement the CONCAT() function to concatenate two columns. Here, we are concatenating columns StudentName and StudentAge. The query is as follows −

mysql> select CONCAT(StudentName, ' ',StudentAge) as NameAndAgeColumn from concatenateTwoColumnsDemo;

The following is the output displaying the concatenated columns −

+------------------+
| NameAndAgeColumn |
+------------------+
| Sam 21           |
| David 24         |
| Carol 22         |
| Johnson 19       |
+------------------+
4 rows in set (0.00 sec)
raja
Published on 10-Jan-2019 17:34:18
Advertisements