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

Viewed 61783

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?

10 Answers

I have this work around with example. Hope this helps. Just go to SQL server, select new query and CP following query:

DECLARE @NULL_SAMLES TABLE
       (
       NS_ID INT IDENTITY(1,1) PRIMARY KEY CLUSTERED NOT NULL
      ,COL_01 VARCHAR(10) NULL
      ,COL_02 VARCHAR(10) NULL
      ,COL_03 VARCHAR(10) NULL
      ,COL_04 VARCHAR(10) NULL
   )

   INSERT INTO @NULL_SAMLES(COL_01,COL_02,COL_03,COL_04)
   VALUES
    ('A','B','C','D')
   ,(' ' ,'B','C','D')
   ,(' ',NULL,'C','D')
   ,('A','B',NULL,'D')
   ,('A','B','C',NULL)
   ,(NULL,'B',NULL,'D')
   ,(NULL,'B','C',NULL)
   ,('A',NULL,'C',NULL)
   ,('A',NULL,NULL,'D')
   ,('A',NULL,NULL,NULL)
   ,(NULL,'B',NULL,NULL)
   ,(NULL,NULL,'C',NULL)
   ,(NULL,NULL,NULL,'D')


   SELECT
        NS.COL_01
       ,NS.COL_02
       ,NS.COL_03
       ,NS.COL_04,
      Stuff(  
        Coalesce(', ' + nullif(NS.COL_01, ''), '') 
      + Coalesce(', ' + nullif(NS.COL_02, ''), '') 
      + Coalesce(', ' + nullif(NS.COL_03, ''), '') 
      +Coalesce(', ' + nullif(NS.COL_04, ''), '')
      , 1, 1, '') AS CONC_COLS
   FROM @NULL_SAMLES NS

Don't underestimate the simple power of the CASE statement, which can be concatenated. Here's a self-contained example you can run as-is:

SELECT
CASE WHEN x.FIRST_NAME IS NULL THEN x.FIRST_NAME ELSE x.FIRST_NAME || ' ' END || 
CASE WHEN x.MIDDLE_NAME IS NULL THEN x.MIDDLE_NAME ELSE x.MIDDLE_NAME  || ' ' END || 
x.LAST_NAME
FROM (SELECT 'John' AS FIRST_NAME, NULL AS MIDDLE_NAME, 'Doe' AS LAST_NAME FROM DUAL) x;
Related