Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concat Values In MySQL Query(To Handle Null Values)

Tags:

mysql

I am writing a PHP and MySQL application in which i have to concatenate multiple column values into one single column.I would have used the concat() function,but it does not handle null values,and the concat_ws(),which does not return the result in the output i want. What i need can be achieved in the Oracle database like this:

 Select 'The Surname Is'||last_name from employees;

My Issue is how can i achieve this same result with MySQL..without using the above named functions?

like image 326
ewom2468 Avatar asked Dec 16 '11 06:12

ewom2468


4 Answers

A little trick: Use empty string like separator with CONCAT_WS (Some times you wan't insert white spaces)

CONCAT_WS('','The Surname Is:',lastname) 
FROM `employees`
like image 79
Curlas Avatar answered Sep 27 '22 00:09

Curlas


CONCAT with IFNULL:

SELECT
  CONCAT('The Surname Is ', IFNULL(last_name, 'sadly not available'))
FROM `employees`
like image 26
Filip Roséen - refp Avatar answered Sep 23 '22 00:09

Filip Roséen - refp


Use coalesce to concat an empty string

select concat(coalesce(null, ''));
like image 25
ajreal Avatar answered Sep 26 '22 00:09

ajreal


@Minesh: CONCAT_WS does not 'take care' of NULL values. To illustrate this...

CONCAT_WS("~",house.name,house.address,house.type)

In the above example, if house.address is NULL the returned result will not contain a neat double tilda (~~) as expected. It will be a tilda separated list with only 1 tilda. eg "fun House~mansion"

like image 37
Martin Joiner Avatar answered Sep 23 '22 00:09

Martin Joiner