Spaces when concatenating multiple columns and one column is null - Oracle

dstnrgrs picture dstnrgrs · Aug 14, 2012 · Viewed 57.6k times · Source

I need to concatenate several columns into one, with spaces between each value. The problem is when one value is null, I end up with a double space between two values.

Example

SELECT (FIRST_NAME || ' ' || MIDDLE_NAME || ' ' || LAST_NAME
  FROM TABLE_A;

If the middle name happens to be NULL, then I end up with two spaces between the first and last name. Any way to get around this and only have one space when there's a null value?

Answer

D'Arcy Rittich picture D'Arcy Rittich · Aug 14, 2012
SELECT TRIM(TRIM(FIRST_NAME || ' ' || MIDDLE_NAME) || ' ' || LAST_NAME)   
FROM TABLE_A;