Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to Concatenate two or more string in MySQL

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 341
    Comment on it

    This article explains the MySQL string functions which are used to concatenate two or more strings.


    1. CONCAT : CONCAT() function is used to generate a string by concatenating two or more strings. The function take one or more strings as arguments and returns a string after concatenating the arguments.


    Syntax : CONCAT(string1, string2,)


    Note :

    • The function requires at least one parameter, otherwise it generate error.
    • If arguments are not in binary form, the result also the nonbinary string.
    • If any argument contains a binary string, than result also a binary string.
    • The numeric type argument is convert into its equivalent nonbinary string.
    • With any NULL argument, the function also return NULL

    2. CONCAT_WS : CONCAT_WS() also known as Concatenate With Separator is another form of CONCAT() function to concatenate strings with separator. The first argument string is used as separator for other arguments. The separator string is added between strings to concatenate them.The separator can also be a string, if separator is NULL the function also return NULL.


    Syntax : CONCAT_WS(separator, string1, string2,......)


    Example : To see these functions in detail, Suppose we have an employee table, which have the following records:


    id first_name last_name city
    EMP_001 Amit Kumar Raipur
    EMP_002 Rajiv Saxena Delhi
    EMP_003 Deepak Singh Dehradun
    EMP_004 Rahul Rawat Mumbai

    Now, suppose you want to concatenate the first and last name of all employees


    Using CONCAT():

    <?php
    $query = "SELECT CONCAT (first_name, ' ', last_name) AS EMP_NAME FROM `employee`";
    ?>
    

    Output :

    EMP_NAME
    Amit Kumar
    Rajiv Saxena
    Deepak Singh
    Rahul Rawat

    Let take another example, suppose you want to concatenate the id also with first and last name of employees into given format : id-first_name-last_name.


    Using CONCAT_WS() :

    <?php
    $query = "SELECT CONCAT_WS ('-', id, first_name, last_name) AS RESULT FROM `employee`";
    ?>
    

    Output :

    RESULT
    EMP_001-Amit-Kumar
    EMP_002-Rajiv-Saxena
    EMP_003-Deepak-Singh
    EMP_004-Rahul-Rawat

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: