abbas abbas - 1 year ago 152
SQL Question

Sql Server - Alternative of doing a RTRIM/LTRIM in the where clause

I hava a column name which is a varchar

I want to filter all results where name is an empty string...

select name
from tblNames
where name <> ''

What I want to do is:

select name
from tblNames
where Ltrim(RTrim(name)) <> ''

I want to apply a trim on name in the where clause but I have read a few articles mentioning the performance issue of functions inside the where clause

I want a solution to this without hurting performance

Answer Source

Standard behaviour in SQL-Server is that

'      ' = ''

is TRUE, because trailing spaces are ignored. From MSDN support:

SQL Server follows the ANSI/ISO SQL-92 specification (Section 8.2, , General rules #3) on how to compare strings with spaces. The ANSI standard requires padding for the character strings used in comparisons so that their lengths match before comparing them. The padding directly affects the semantics of WHERE and HAVING clause predicates and other Transact-SQL string comparisons. For example, Transact-SQL considers the strings 'abc' and 'abc ' to be equivalent for most comparison operations.

The only exception to this rule is the LIKE predicate. ...

So, your condition WHERE name <> '' should work fine, and not include any strings where there are only spaces.