Why does using an Underscore character in a LIKE filter give me all the results?
As you want to specifically search for a wildcard character you need to escape that
This is done by adding the ESCAPE
clause to your LIKE
expression. The character that is specified with the ESCAPE
clause will "invalidate" the following wildcard character.
You can use any character you like (just not a wildcard character). Most people use a \
because that is what many programming languages also use
So your query would result in:
select *
from Manager
where managerid LIKE '\_%' escape '\'
and managername like '%\_%' escape '\';
But you can just as well use any other character:
select *
from Manager
where managerid LIKE '#_%' escape '#'
and managername like '%#_%' escape '#';
Here is an SQLFiddle example: http://sqlfiddle.com/#!6/63e88/4
The underscore is the wildcard in a LIKE
query for one arbitrary character.
Hence LIKE %_%
means "give me all records with at least one arbitrary character in this column".
You have to escape the wildcard character, in sql-server with []
around:
SELECT m.*
FROM Manager m
WHERE m.managerid LIKE '[_]%'
AND m.managername LIKE '%[_]%'
See: LIKE (Transact-SQL)
Demo
Modify your WHERE
condition like this:
WHERE mycolumn LIKE '%\_%' ESCAPE '\'
This is one of the ways in which Oracle supports escape characters. Here you define the escape character with the escape
keyword. For details see this link on Oracle Docs.
The '_'
and '%'
are wildcards in a LIKE
operated statement in SQL.
The _
character looks for a presence of (any) one single character. If you search by columnName LIKE '_abc'
, it will give you result with rows having 'aabc'
, 'xabc'
, '1abc'
, '#abc'
but NOT 'abc'
, 'abcc'
, 'xabcd'
and so on.
The '%'
character is used for matching 0 or more number of characters. That means, if you search by columnName LIKE '%abc'
, it will give you result with having 'abc'
, 'aabc'
, 'xyzabc'
and so on, but no 'xyzabcd'
, 'xabcdd'
and any other string that does not end with 'abc'
.
In your case you have searched by '%_%'
. This will give all the rows with that column having one or more characters, that means any characters, as its value. This is why you are getting all the rows even though there is no _
in your column values.