1

I have blanks in my name column in sql query. How can I replace to show as null.

SELECT Name from table
MT0
  • 143,790
  • 11
  • 59
  • 117
Aruna Raghunam
  • 903
  • 7
  • 22
  • 43

3 Answers3

2

The TRIM function provides this feature.

It is used like this:

select TRIM(Name) from table

It will remove leading and trailing spaces from the results for field Name.

René Hoffmann
  • 2,766
  • 2
  • 20
  • 43
  • 2
    An empty string `''` and a null are equivalent in Oracle when the data type is a (N)VARCHAR or a (N)VARCHAR2. This won't do anything: http://stackoverflow.com/questions/13278773/null-vs-empty-string-in-oracle – Ben Apr 12 '17 at 13:23
  • 1
    @Ben Did not know that. Then `TRIM` should suffice. I changed my answer accordingly. – René Hoffmann Apr 12 '17 at 13:26
  • Depending on your client application it may display null in different ways. To ensure that you always see the string 'null' wrap the TRIM in a NVL displaying 'null' when the trimmed name is null. – BriteSponge Apr 12 '17 at 15:34
0

Maybe you are talking of spaces?

Here is how to remove any commonly known "blank" chars:

  • with regexp_replace (interestingly... just to notice the [[:space:]])

select '<'||
  regexp_replace(
   'a'||CHR(9)||' b'||CHR(10)||CHR(11)
      ||'c'||CHR(12)||CHR(13)||' d'
 , '[[:space:]]','')
||'>' 
from dual;
  • more efficient: avoid regexp_replace...: use TRANSLATE!

select '<'||
  TRANSLATE(
   'a'||CHR(9)||' b'||CHR(10)||CHR(11)
      ||'c'||CHR(12)||CHR(13)||' d' -- complicate string with blank
  ,'A'||CHR(9)||CHR(10)||CHR(11)||CHR(12)||CHR(13)||' '
  ,'A') -- this 'A' is a trick to replace by null ('')
||'>'    -- to show where string stops
from dual;
J. Chomel
  • 8,193
  • 15
  • 41
  • 69
0

TRIM removes the blank character from left and right, so if your string only consists of blanks then you get an empty string, which is NULL in Oracle.

select trim(name) from mytable;

This would also change ' Mary Smith ' to 'Mary Smith', but I guess you wouldn't mind :-)

If, however, you want to consider any whitespace, e.g. tabs, too, then TRIM doesn't suffice. You can use REGEXP_REPLACE then to replace all names that only consist of whitespace with null.

regexp_replace(name, '^[[:space:]]*$', null) from mytable;

If you also want to trim whitespace from any names (so ' Mary Smith ' becomes 'Mary Smith' again) then:

select regexp_replace(name, '^[[:space:]]*([^[:space:]]*)[[:space:]]*', '\1') from mytable;
Thorsten Kettner
  • 89,309
  • 7
  • 49
  • 73