Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spaces in WHERE clause for SQL Server [duplicate]

Tags:

sql

sql-server

I want to find out the records in which a certain column contains exactly one space and nothing else. So I wrote the first of the following queries:

select COUNT(*)
from mytable
where col = ' ' -- One space

select COUNT(*)
from mytable
where col = '  ' -- Two spaces

select COUNT(*)
from mytable
where col = '  ' -- Three spaces

However, all three queries return the exact same records. Does Microsoft SQL Server not distinguish between the amount of spaces? How can I query exactly for one, two or more spaces?

like image 769
Koruba Avatar asked Oct 01 '18 13:10

Koruba


People also ask

Does SQL ignore trailing spaces?

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

Do extra spaces matter in SQL?

Whitespace is optional in pretty much any language where it is not absolutely necessary to preserve boundaries between keywords and/or identifiers. You could write code in C# that looked similar to your SQL, and as long as the compiler can still parse the identifiers and keywords, it doesn't care.

Can you use WHERE clause twice in SQL?

But yes, you can use two WHERE.


2 Answers

Yes, it ignores trailing spaces in comparisons.

You can try to append a delimiting character.

SELECT count(*)
FROM mytable
WHERE col + 'X' = ' X';
like image 178
sticky bit Avatar answered Nov 15 '22 21:11

sticky bit


You can combine DATALENGTH clause with your query:

   select COUNT(*)
   from mytable
   where col = ' '
   and DATALENGTH(col) = 1
like image 38
S.K. Avatar answered Nov 15 '22 22:11

S.K.