T-SQL: Trailing Spaces And String Comparison

Here’s a useful tidbit regarding trailing spaces and SQL Server queries. Note the count of the results from the query below. Because SQL Server follows the ANSI/ISO SQL-92 specification, the string ‘test’ and ‘test    ‘ (with spaces at the end) are treated as the same value; only the length will be different. See How SQL Server Compares Strings with Trailing Spaces for more information.

;WITH StringsToTest AS
(
  SELECT 'test       ' AS test
  UNION ALL
  SELECT 'test'
  UNION ALL
  SELECT '      test'
)
SELECT COUNT(test), test
FROM StringsToTest 
GROUP BY test

Hope this helps!

This entry was posted in T-SQL. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *