Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL char to varchar comparison works, why?

Why does the following return a result when the target column in the where clause is a char(20)?

declare @pallettag varchar(20)
set @pallettag = '168531'
--set @pallettag = @pallettag + SPACE(20 - Len(@pallettag))

select s.ROWID, s.SUBLOTCODE + '*', @pallettag + '*'
from IMSUBLOT as s
where s.SUBLOTCODE = @pallettag

s.SUBLOTCODE is defined as char(20) and I would expect to get a result only if I uncomment the third line where I added the needed spaces.

like image 585
Jon Reopelle Avatar asked Nov 23 '11 18:11

Jon Reopelle


People also ask

Can you compare CHAR and VARCHAR SQL?

CHAR takes up 1 byte per character. So, a CHAR(100) field (or variable) takes up 100 bytes on disk, regardless of the string it holds. VARCHAR is a variable length string data type, so it holds only the characters you assign to it. VARCHAR takes up 1 byte per character, + 2 bytes to hold length information.

Why CHAR is faster than VARCHAR?

Because of the fixed field lengths, data is pulled straight from the column without doing any data manipulation and index lookups against varchar are slower than that of char fields. CHAR is better than VARCHAR performance wise, however, it takes unnecessary memory space when the data does not have a fixed-length.

How does SQL string comparison work?

In SQL Server a string comparison is done in alphabetical order. That is "allan" is greater than "alan" because alphabetically "alan" comes before "allan". So, numbers are treated the same when doing string comparison, they are treated in alphabetical order...so, '2' is greater than '12'...


1 Answers

Trailing spaces are ignored in string comparisons in SQL Server except for expressions on the right in a LIKE comparison.

SELECT CASE
         WHEN '168531' = '168531                ' THEN 'Y'
         ELSE 'N'
       END AS [=],
       CASE
         WHEN '168531' LIKE '168531                ' THEN 'Y'
         ELSE 'N'
       END AS [Like RHS],
       CASE
         WHEN '168531                ' LIKE '168531' THEN 'Y'
         ELSE 'N'
       END AS [Like LHS]    

Returns

=    Like RHS Like LHS
---- -------- --------
Y    N        Y
like image 105
Martin Smith Avatar answered Nov 08 '22 05:11

Martin Smith