Why does using an Underscore character in a LIKE filter give me all the results? - sql

I wrote the below SQL query with a LIKE condition:
SELECT * FROM Manager
WHERE managerid LIKE '_%'
AND managername LIKE '%_%'
In the LIKE I want to search for any underscores %_%, but I know that my columns' data has no underscore characters.
Why does the query give me all the records from the table?
Sample data:
create table Manager(
id int
,managerid varchar(3)
,managername varchar(50)
);
insert into Manager(id,managerid,managername)values(1,'A1','Mangesh');
insert into Manager(id,managerid,managername)values(2,'A2','Sagar');
insert into Manager(id,managerid,managername)values(3,'C3','Ahmad');
insert into Manager(id,managerid,managername)values(4,'A4','Mango');
insert into Manager(id,managerid,managername)values(5,'B5','Sandesh');
Sql-Fiddle

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.

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

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

Underscore is a wildcard for something.
for example
'A_%' will look for all match that Start whit 'A' and have minimum 1 extra character after that

In case people are searching how to do it in BigQuery:
An underscore "_" matches a single character or byte.
You can escape "\", "_", or "%" using two backslashes. For example, "\%". If you are using raw strings, only a single backslash is required. For example, r"\%".
WHERE mycolumn LIKE '%\\_%'
Source: https://cloud.google.com/bigquery/docs/reference/standard-sql/operators

You can write the query as below:
SELECT * FROM Manager
WHERE managerid LIKE '\_%' escape '\'
AND managername LIKE '%\_%' escape '\';
it will solve your problem.

Related

Multiple charactor match with LIKE clause

I need to return the rows that contain both _1 and _2 from the SQL Server table. Below is my query and it returns the rows even both the above conditions are not matched.
As per my knowledge, I can use [ and ] to match multiple values when using the LIKE clause with wild cards.
DECLARE #TempTable AS TABLE (Col VARCHAR(MAX))
INSERT INTO #TempTable VALUES
('001098E2-5995-446F-87DC-BE71D2B30D37_2|69FA4BCD-C90B-4375-B08C-B3615C55500D_2'),
('0025F9BF-995D-4C88-BBD6-4C707A88BC32_1|F53668A8-F819-4309-BC0C-8DE4C2637419_2'),
('007BB00A-3B69-45FC-A265-1EC8B00E011A_2|0701649E-8BFE-4B03-8456-51E2D9169BD5_2|08950E50-80B2-4BDF-9FC7-3AB0AA4587AE_1')
SELECT * FROM #TempTable
WHERE (Col LIKE '%[_1]%' AND Col LIKE '%[_2]%')
I expect not to return 001098E2-5995-446F-87DC-BE71D2B30D37_2|69FA4BCD-C90B-4375-B08C-B3615C55500D_2, but SQL Server returns all 3 records.
Thanks in advance.
SELECT * FROM #TempTable
WHERE (Col LIKE '%[_]1%' AND Col LIKE '%[_]2%')
Using Wildcard Characters As Literals
You can use the wildcard pattern matching characters as literal characters. To use a wildcard character as a literal character, enclose the wildcard character in brackets. The following table shows several examples of using the LIKE keyword and the [ ] wildcard characters.
_ is also a wildcard matching one arbitrary character. You can define an ESCAPE character and escape it to match a regular underscore. You don't need [], i.e. character classes here.
SELECT *
FROM #temptable
WHERE col LIKE '%\_1%' ESCAPE '\'
AND col LIKE '%\_2%' ESCAPE '\';
db<>fiddle
You can use the wildcard pattern matching characters as literal characters.
To use a wildcard character as a literal character, enclose the wildcard character in brackets.
WHERE (Col LIKE '%[_]1%' AND Col LIKE '%[_]2%')
you can also escape the underscore like this
WHERE (Col LIKE '%$_1%' ESCAPE '$')
AND (Col LIKE '%$_2%' ESCAPE '$')

LIKE operator and % wildcard when string contains underscore

I have a table in SQL Server that stores codes. Depending on the nomenclature, some begin with 'DB_' and others with 'DBL_'. I need a way to filter the ones that start with 'DB_', since when I try to do it, it returns all the results.
CREATE TABLE CODES(Id integer PRIMARY KEY, Name Varchar(20));
INSERT INTO CODES VALUES(1,'DBL_85_RC001');
INSERT INTO CODES VALUES(2,'DBL_85_RC002');
INSERT INTO CODES VALUES(3,'DBL_85_RC003');
INSERT INTO CODES VALUES(4,'DB_20_SE_RC010');
INSERT INTO CODES VALUES(5,'DB_20_SE_RC011');
SELECT * FROM CODES where Name like 'DB_%';
The result that returns:
1|DBL_85_RC001
2|DBL_85_RC002
3|DBL_85_RC003
4|DB_20_SE_RC010
5|DB_20_SE_RC011
Expected result:
4|DB_20_SE_RC010
5|DB_20_SE_RC011
_ is a wildcard for a single character in a LIKE expression. Thus both 'DB_' and 'DBL' are LIKE 'DB_'. If you want a literal underscore you need to put it in brackets ([]):
SELECT *
FROM CODES
WHERE [Name] LIKE 'DB[_]%';
The underscore is a wildcard in SQL Server. You can escape it:
where name like 'DB$_%' escape '$'
You could also use left():
where left(name, 3) = 'DB_'
However, this is not index- and optimizer friendly.

Escaping wildcards in LIKE

How do I escape wildcards (_ and %) when using a SQL LIKE operator in Oracle?
I came to a silly issue today. I need to search for the presence of an underscore _ on a varchar column using LIKE. It doesn't work -- as expected -- since underscores are wildcards according to SQL. Here's my (simpified) code:
create table property (
name varchar(20),
value varchar(50)
);
insert into property (name, value) values ('port', '8120');
insert into property (name, value) values ('max_width', '90');
insert into property (name, value) values ('taxrate%', '5.20');
I tried the following queries in PostgreSQL and they return the rows I want:
select * from property where name like '%\_%'; -- should return: max_width
select * from property where name like '%\%%'; -- should return: taxrate%
Unfortunately it doesn't work in Oracle 12c. Is there a "standard" way of escaping wildcards? Or at least something that works in Oracle?
You can use the escape syntax
You can include the actual characters % or _ in the pattern by using the ESCAPE clause, which identifies the escape character. If the escape character precedes the character % or _ in the pattern, then Oracle interprets this character literally in the pattern rather than as a special pattern-matching character.
So you can do:
select * from property where name like '%\_%' escape '\';
NAME VALUE
-------------------- --------------------------------------------------
max_width 90
select * from property where name like '%\%%' escape '\';
NAME VALUE
-------------------- --------------------------------------------------
taxrate% 5.20

Use hyphen ("-") in SQLite LIKE clause

I am trying to use a hyphen in a SQLite LIKE string, but it is not working.
Sample search string:
SELECT Name from Table where Name LIKE 'abc - %'
This returns zero results. Whereas the following will, of course, return all names that start with 'abc'.
SELECT Name from Table where Name LIKE 'abc%'
I've tried using the ESCAPE clause like this:
SELECT Name from Table where Name LIKE 'abc !-' ESCAPE '!'
But again, no Names are returned.
Oddly, all of the other questions seem to refer to escaping the '%' and '_' characters, but none address the escaping of the '-' (hyphen).
How can I do this?
After further investigation, it appears that the lack of results when a hyphen is present is a bug in SQLiteStudio (using V3.1.0) the GUI I'm using with SQLite. When I tried the SQL statement (with the '-' and without the ESCAPE clause) in the Command Line Interface, it returned the expected results.

LIKE contains %

I have record in table like 'abc 100% text'.
I want to search all the records that contain 100%.
What will be LIKE query?
SELECT * FROM TABLE where ColName LIKE '100%%'
above query returns wrong results.
Thanks.
SELECT * FROM TABLE where ColName LIKE '%100[%]%'
Have a look at Using Wildcard Characters As Literals
You can use the wildcard pattern matching characters as literal characters. To use a wildcard character as a literal character, enclose the wildcard character in brackets.
SELECT columns FROM table WHERE column LIKE '%[%]%'
or
SELECT columns FROM table WHERE column LIKE '%\%%' ESCAPE '\'
as described in http://web.archive.org/web/20150519072547/http://sqlserver2000.databases.aspfaq.com:80/how-do-i-search-for-special-characters-e-g-in-sql-server.html
Additionally, you can use escape charaters...
LIKE '%100^%%' ESCAPE '^'
http://web.archive.org/web/20150519072547/http://sqlserver2000.databases.aspfaq.com:80/how-do-i-search-for-special-characters-e-g-in-sql-server.html
Use a backslash to escape:
SELECT * FROM TABLE where ColName LIKE '%100\%%';
You may need to try this:
SELECT * FROM TABLE where ColName LIKE '%100\%%' ESCAPE '\';