10

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?

5 Answers 5

28

CONCAT with IFNULL:

SELECT
  CONCAT('The Surname Is ', IFNULL(last_name, 'sadly not available'))
FROM `employees`
Sign up to request clarification or add additional context in comments.

Comments

10

@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"

3 Comments

it does remove it along with it's separator, where is the problem in that? it's the neat solution unless you wanted to do something else
I consider it bad because the function performs 2 different tasks, the second of which is not suggested by the function name. First it concatenates, great, thanks, that's what I wanted. Then it removes blank string list items, woah, I didn't ask you to do that. The function should be called CONCAT_NN_WS() where the NN stands for "Not Nulls". If I ask my software to just concatenate 5 things into a list, I expect a 5 item list. I don't then expect the software to then say "Oh by the way, I emptied the bins, fed the cat and phoned your mum to invite her for the weekend too"
You're right this will be useful and it should have been implemented (keeping this method as well for other purposes).
9

You can also use CONCAT_WS function which takes care of NULL values

SELECT 
CONCAT_WS(' ','The Surname Is',lastname) 
FROM `employees`

Comments

4

Use coalesce to concat an empty string

select concat(coalesce(null, ''));

Comments

1

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`

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.