What is the advantage of CONCAT_WS() function over CONCAT() function when we want to concatenate the values from the column and any of the columns have NULL as its value?


As we know that CONCAT() function returns NULL if any of the arguments is NULL but CONCAT_WS() function returns NULL only if the first argument i.e. the separator is NULL and it ignores any other NULL. We can say this is the advantage of CONCAT_WS() function over CONCAT() function when we want to concatenate the values from the column and any of the columns have NULL as its value. To understand it, we consider the example from the table ‘Student_name; which have the following data −

mysql> Select * from Student_Name;
+---------+-------+---------+
| FName   | Mname | Lname   |
+---------+-------+---------+
| Rahul   | NULL  | Singh   |
| Gaurav  | Kumar | NULL    |
| Harshit | NULL  | Khurana |
| Yash    | Pal   | Sharma  |
+---------+-------+---------+
4 rows in set (0.00 sec)

Now, suppose if we want to concatenate the values of Fname, Mname and Lname columns then following would be the output −

mysql> Select CONCAT(Fname,Mname,Lname)AS Name from Student_Name;
+---------------+
| Name          |
+---------------+
| NULL          |
| NULL          |
| NULL          |
| YashPalSharma |
+---------------+
4 rows in set (0.00 sec)

But, if we will use CONCAT_WS() function then it will ignore the NULL as did in the following query −

mysql> Select CONCAT_WS(' ',Fname,Mname,Lname)AS Name from student_name;
+-----------------+
| Name            |
+-----------------+
| Rahul Singh     |
| Gaurav Kumar    |
| Harshit Khurana |
| Yash Pal Sharma |
+-----------------+
4 rows in set (0.00 sec)

Updated on: 22-Jun-2020

96 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements