Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 867
dstnrgrs Avatar asked Aug 14 '12 16:08

dstnrgrs


People also ask

How do I add a space when concatenating in Oracle?

We can concatenate a space character using the || operator. In this example, we have used the || operator to add a space character between the values Dave and Anderson. This will prevent our values from being squished together.

How do you concatenate null values?

When you concatenate any string with a NULL value, it will result in NULL. To avoid this, you can use the COALESCE function. The COALESCE function returns the first non-Null value. So, when there is a value in the column that is not null, that will be concatenated.

How do I concatenate more than two columns in Oracle?

Oracle String concatenation allows you to append one string to the end of another string. To display the contents of two columns or more under the name of a single column, you can use the double pipe concatenation operator (||).


1 Answers

SELECT TRIM(TRIM(FIRST_NAME || ' ' || MIDDLE_NAME) || ' ' || LAST_NAME)   
FROM TABLE_A; 
like image 185
D'Arcy Rittich Avatar answered Nov 07 '22 02:11

D'Arcy Rittich