8

I have a data with a column for the first name and a column for the last name. I try to combine the them into one column via code:

SELECT GROUP_CONCAT_UNQUOTED(full_name,' ') 
from (Select first_name as check from [DATA]), 
     (select last_name  as check from [DATA])

But it returns a one row string with

Anna Alex Emma Sean .... Miller Smith White ...

but what I wanted was actually a column like

Anna Miller
Alex Smith
Emma White
...

Can you please tell me what I should do differently? Thanks!

2 Answers 2

19

You need to use CONCAT and the trim functions

SELECT CONCAT(rtrim(ltrim(first_name)),' ',rtrim(ltrim(last_name))) AS full_name
FROM
  (SELECT 'Anna' AS first_name,
          ' Miller ' AS last_name),
3
  • Thank you, it works in most of the cases but if the value for first_name or last_name is null, it returns null. I tried with string(first_name) but it stays null. I'd expect it to return e.g. Sean null or Sean NoName.
    – Ilja
    Commented May 5, 2015 at 7:45
  • 2
    You need to add IFNULL(first_name,'null'), IFNULL(first_name,'NoName')
    – Pentium10
    Commented May 5, 2015 at 8:19
  • 2
    Also SELECT RTRIM(LTRIM(first_name))+' '+RTRIM(LTRIM(last_name)) would work (+ instead of CONCAT) Commented May 5, 2015 at 21:15
4

You can also use the double pipe || concatenation operator for concatenation of strings (see here for more info):

select 
    trim(first_name) || ' ' || trim(last_name)
from
    ...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.