Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the SQL Server ignore the empty space at the end automatically?

I wrote a query

SELECT * FROM Users WHERE UserName = 'admin '

by mistaken typing. But I found that the result is as the same as

SELECT * FROM Users WHERE UserName = 'admin'

It seems that the empty space at the end is ignored by SQL Server automatically.

Can anybody tell me why?

FYI, the column UserName is of type nvarchar(MAX).

like image 891
Jailu Lee Avatar asked Jul 26 '13 08:07

Jailu Lee


People also ask

Does SQL Server ignore trailing spaces?

Takeaway: According to SQL Server, an identifier with trailing spaces is considered equivalent to the same identifier with those spaces removed.

How do you remove trailing spaces in SQL query?

SQL Server TRIM() Function The TRIM() function removes the space character OR other specified characters from the start or end of a string. By default, the TRIM() function removes leading and trailing spaces from a string.

How does SQL Server handle empty values?

Handling the Issue of NULL and Empty Values SQL Server provides 2 functions for doing this; (i) the ISNULL; and (ii) the COALESCE. (2) COALESCE takes N parameters as input (N>=2). By having N expressions as input parameters it returns the first expression that IS NOT NULL.


2 Answers

SQL Server is following the ANSI/ISO standard for string comparison.

The article How SQL Server Compares Strings with Trailing Spaces explains this in detail.

SQL Server follows the ANSI/ISO SQL-92 specification... 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.

Also, as explained in the article, if you compare with LIKE you do not get this behaviour.

like image 132
Ian Preston Avatar answered Nov 09 '22 03:11

Ian Preston


If you are trying like this

SELECT * 
FROM Users 
WHERE UserName = 'admin '

empty spaces are ignored SQL Server. But if you try like this

SELECT * 
FROM Users 
WHERE UserName Like 'admin '

It consider the empty spaces also.

DECLARE @Person1 varchar(50)='admin'
SELECT 1  WHERE @Person1 = 'admin '
SELECT 1  WHERE @Person1 like 'admin '

The result of the above query set is

enter image description here

like image 33
Nithesh Narayanan Avatar answered Nov 09 '22 03:11

Nithesh Narayanan