5

in mysql:

select 'a' = 'a     ';

return 1

ripper234
  • 222,824
  • 274
  • 634
  • 905

5 Answers5

5

You're not the first to find this frustrating. In this case, use LIKE for literal string comparison:

SELECT 'a' LIKE 'a    ';    //returns 0
Sampson
  • 265,109
  • 74
  • 539
  • 565
  • Just be careful that any wildcard characters (`%` or `_` ) in the right hand operand are properly escaped. – eggyal Jan 26 '15 at 17:28
3

This behavior is specified in SQL-92 and SQL:2008. For the purposes of comparison, the shorter string is padded to the length of the longer string.

From the draft (8.2 <comparison predicate>):

If the length in characters of X is not equal to the length in characters of Y, then the shorter string is effectively replaced, for the purposes of comparison, with a copy of itself that has been extended to the length of the longer string by concatenation on the right of one or more pad characters, where the pad character is chosen based on CS. If CS has the NO PAD characteristic, then the pad character is an implementation-dependent character different from any character in the character set of X and Y that collates less than any string under CS. Otherwise, the pad character is a <space>.

In addition to the other excellent solutions:

select binary 'a' = 'a   '
jspcal
  • 50,847
  • 7
  • 72
  • 76
2

I googled for "mysql string" and found this:

In particular, trailing spaces [using LIKE] are significant, which is not true for CHAR or VARCHAR comparisons performed with the = operator

Ken
  • 437
  • 7
  • 10
0

From the documentation:

All MySQL collations are of type PADSPACE. This means that all CHAR and VARCHAR values in MySQL are compared without regard to any trailing spaces

The trailing spaces are stored in VARCHAR in MySQL 5.0.3+:

CREATE TABLE t_character (cv1 CHAR(10), vv1 VARCHAR(10), cv2 CHAR(10), vv2 VARCHAR(10));

INSERT
INTO    t_character
VALUES  ('a', 'a', 'a ', 'a ');

SELECT  CONCAT(cv1, cv1), CONCAT(vv2, vv1)
FROM    t_character;

but not used in comparison.

Quassnoi
  • 413,100
  • 91
  • 616
  • 614
0

Here's another workaround that might help:

select 'a' = 'a     ' and length('a') = length('a     ');

returns 0

Ike Walker
  • 64,401
  • 14
  • 110
  • 109
  • I think it's probably more correct to use `CHAR_LENGTH()` than `LENGTH()`—whilst highly unlikely, it's *conceivable* that in some obscure character set the encoding of both strings could occupy the same number of bytes whilst representing a different number of characters. – eggyal Jul 26 '16 at 11:26
  • @eggyal I agree! I always use `CHAR_LENGTH()` these days, but I suppose I wasn't quite so careful 6 years ago :) – Ike Walker Aug 10 '16 at 13:35