Reputation: 361
I ran these two queries in PostgreSQL and got different results. I was wondering if someone could explain why. Is this the same in MicrosoftSQL, MySQL, and other databases?
select 'teststring%' like 'teststring'; --returns False
select 'teststring' like 'teststring%'; --returns True
Upvotes: 0
Views: 137
Reputation: 2731
Because 'teststring%'
is actually not like 'teststring'
.
But 'teststring'
is like 'teststring%'
.
This should happen in every database.
LIKE
operator is not commutative. If the rightside string has no wildcard character (ampersand or underscore) it behaves as =
(as a side effect).
Algorithm for LIKE
handles the rightside this way:
The leftside string has no special meaning to any character.
Upvotes: 3
Reputation: 5631
After the like
pattern, the %
character is considered as escape character
. but it is not the same case for the first %
(which is before like
)
to escape the character %
you have to add \
(This the default one in PostgreSQL, you can choose another using the escape
clause): \%
For example:
select 'teststring%' like 'teststring'; -- returns false
select 'teststring' like 'teststring%'; -- returns true
select 'teststring%' like 'teststring%'; -- returns true
select 'teststring%' like 'teststring\%'; -- returns true
Upvotes: 1