in this tutorial, We’ll concatenate two or multiple columns in MySQL.We will select the values and concat multiple columns using MySQL inbuilt method.
It can also achieve the same thing using programmatically. You need to select columns fields value separately from MySQL Table and store their values in the single variable after concat their values.
Case 1: I am assuming, We have firstname, lastname column within our DataBase Table. Concatenate firstname, lastname columns values in a single string form.
There are two functions for doing this –
- CONCAT
- CONCAT_WS
Above function work for concate multiple columns :
CONCAT
This function is used to concatenate multiple columns or strings into a single one. The method arguments are separated by a comma.
Syntax –
CONCAT( column1, column2, … ) OR CONCAT ( string1, string2, … )
MySQL Query to Concatenate table Columns
SELECT CONCAT( firstname, " ", lastname ) AS fullname, salary FROM employees
CONCAT_WS
The CONCAT_WS()
function is used to add multiple string values and makes them a single string value. The main difference between CONCAT()
and CONCAT_WS()
is that we can define separator. It also let you define separator ( ” “, “, “, ” – “, etc.).
Syntax –
CONCAT_WS( SEPARATOR, column1, column2, … ) OR CONCAT ( SEPARATOR, string1, string2, … )
Example concatenate Using CONCAT_WS()
SELECT username, CONCAT_WS( " ", firstname, lastname ) AS fullname FROM users