1

Here is a sample of the issue:

SELECT 'True'
WHERE 'Hello      ' IN ('Hello', 'Goodbye', 'Hello  ')

Currently this returns 'True' because SQL ignores trailing spaces when comparing VARCHAR. In this related question, this can be solved by using LIKE, however this won't work with an IN condition.

How can I ensure that the comparison takes into account the trailing spaces, specifically when using the IN condition?

Edit: My list of acceptable values can include items with trailing spaces. Looking to compare exact values essentially (i.e 'Hello ' won't match with 'Hello ')

Mackija
  • 307
  • 2
  • 14

3 Answers3

2

Assuming that your list of acceptable values do not have trailing spaces, perhaps you could use:

SELECT 'True'
WHERE 'Hello      ' IN ('Hello', 'Goodbye') AND 'Hello      ' NOT LIKE '% '
Lee Mac
  • 15,615
  • 6
  • 32
  • 80
  • Good solution but unfortunately my list does have the potential to have those trailing spaces, I will update my question – Mackija Nov 08 '18 at 13:49
1

You could add a non-space char to the end of your search temrs:

DECLARE @Terminator char(1) = '|';

SELECT 'True'
WHERE 'Hello      ' + @Terminator  IN ('Hello' + @Terminator , 'Goodbye' + @Terminator)

This will force the comparison to take into account the trailing spaces while keeping everything seargable. (I assume you want to use columns either on the left or on the right side of the IN operator)

Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
  • This is a good solution, one downside would be that I would have to add the terminator to each of items which I'd like to avoid if possible (I have a long list). Also trying to avoid putting that list into a table – Mackija Nov 08 '18 at 13:46
  • 1
    @Mackija Don't avoid putting the values in a table. I think this will be the correct course of action. – UnhandledExcepSean Nov 08 '18 at 14:20
1

I can think of this solution on top of my head:

SELECT 'True'
WHERE reverse('Hello      ') IN (reverse('Hello'), reverse('Goodbye'))

Basically this forces to compare string using reverse function.

But Zohar's solution below is most performance driven solution.

SELECT 'True'
WHERE 'Hello      '+'|' IN ('Hello'+'|', 'Goodbye'+'|')
Prabhat G
  • 2,974
  • 1
  • 22
  • 31