Web Info and IT Lessons Blog...

Monday, 15 December 2014

MySql CONCAT() Function

The previous lesson of MySql Lessons Series was about MySql FIND_IN_SET and MySql LOCATE functions and in this lesson we will learn about MySql CONCAT() function.

MySql CONCAT Function

MySql CONCAT() function is used to join two strings as a single string. MySql CONCAT() can be used to join two columns of a table and fetch the result as a single string or append characters to a column in the query result. The basic structure of MySql CONCAT() function is given below:



SELECT ColumnNames, CONCAT(String1, String2) AS ColumnName
FROM TableName WHERE 1


For explanation of MySql CONCAT() function, consider the table shown in the image below:

MySql CONCAT Table

The above image shows a table (user) containing the data of a few users. The first name and last name of users have different columns in the user table. If we want to fetch the first name and last name of users as a single result i. Name, then we can use MySql CONCAT() function to get it done easily i.e


SELECT id, CONCAT(First_Name,Last_Name) AS Name,
Country FROM `user` WHERE 1

The CONCAT() function used in the above query will join the first name and last name of users and fetch the result as Name. Result of the above query is shown in the image below:

MySql CONCAT Result

You can see in the above image, the first name and last name of users are joined and shown as Name but there is no space between the first name and last name of users. If we want to add a space between the first name and the last name, all we have to do is concatenate a space between the first name and the last name i.e


SELECT id, CONCAT(First_Name,' ',Last_Name) AS Name,
Country FROM `user` WHERE 1

The above CONCAT() function in the query will concatenate the first name and last name of users with a space in between.

Related Posts
MySql Replace Function
MySql FIND_IN_SET and MySql Locate
MySql IF Statement
CASE in MySQl

No comments:

Post a Comment