1

I am trying to combine rows and concatenate two columns (name, vorname) in a Postgres query.

This works good like this:

SELECT nummer, 
       array_to_string(array_agg(name|| ', ' ||vorname), '\n') as name
FROM  (
   SELECT DISTINCT
          nummer, name, vorname
   FROM   myTable
   ) AS m
GROUP  BY nummer 
ORDER  BY nummer;

Unfortunately, if "vorname" is empty I get no results although name has a value.

Is it possible get this working:

   array_to_string(array_agg(name|| ', ' ||vorname), '\n') as name

also if one column is empty?

2
  • Years later, I just want to say a big 'thank you'. This only came up recently in a project. Saved my life. Commented Mar 25, 2017 at 3:54
  • great to hear ;) Commented Mar 25, 2017 at 20:09

2 Answers 2

1

Use coalesce to convert NULL values to something that you can concatenate:

array_to_string(array_agg(name|| ', ' ||coalesce(vorname, '<missing>')), '\n')

Also, you can concatenate strings directly without collecting them to an array by using the string_agg function.

Sign up to request clarification or add additional context in comments.

Comments

1

If you have 9.1, then you can use third parameter for array_to_string - null string

array_to_string(array_agg(name), ',', '<missing>') from bbb

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.