Search code examples
sqlstringhadooptrim

How to Remove Empty Strings


I'm trying to find a way to trim or remove spaces in what appeared to be empty strings so that when I look for a min value I get a result with characters and not an empty string with spaces.

Originally I tried excluding empty fields ( !="" ) however since the empty strings contain spaces its technically not an empty string so I tried Trimming and still cant get the result set that I need.

select trim(Field_1) as Field_1
from Table_1
where Field_Date between '2019-08-01' and '2019-08-31'
and Field_1 != ""
order by Field_1 asc

The Result Set that I get is:

  • Blank (6 Spaces)
  • Blank (6 Spaces)
  • Blank (6 Spaces)
  • ABC
  • DEF
  • GHI

The Result Set that I Need

  • ABC
  • DEF
  • GHI

Solution

  • It looks like your WHERE condition is not being trimmed whereas your SELECT is.

    In your case you are using Field_1 as the reference in your condition, which appears to refer to the table's column and not the alias you created by saying trim(Field_1) as Field_1

    If you only want results that have no whitespace there is no need to trim() your selected column since your condition enforces that your result can have no whitespace, so why not use trim() in your second condition?

    That way every record's value for Field_1 will be trimmed first and then compared to "".

    How about something like this?

    select Field_1
    from Table_1
    where Field_Date between '2019-08-01' and '2019-08-31'
    and trim(Field_1) != ""
    order by Field_1 asc