Using `_%` together in `LIKE` is not returning exact data - sql

I can guesss it may be easy to answer type question but I am facing it first time, so any help will be more appreciated.
My Query:
SELECT remarks FROM enroll WHERE remarks LIKE 'REC_%'
OUTPUT:
remarks
REC_59161
Reclassify Hedge
Expected Output is only REC_59161. Yes _ is used for matching any single character but I am just looking for achieving my expected output.

_ is a wildcard Character. So that you have to escape it using [].
Query
select remarks
from enroll
where remarks like 'REC[_]%';

The underscore _ character is actually a special character with the LIKE operator, as are %, [] and ^:
https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql
In that article, you'll see that an underscore _ matches any single character.
Use the ESCAPE keyword to define an escape character to allow you to escape the pattern-matching characters. We can use ! as the escape character, so:
WHERE remarks LIKE 'REC!_%' ESCAPE '!'

_ is a wildcard character, Try this :
declare #enroll table (remarks varchar(50));
insert into #enroll values ('REC_59161') , ('Reclassify Hedge');
SELECT remarks FROM #enroll WHERE remarks LIKE 'REC[_]%';
Demo

There are two issues:
It seems that the column is case insensitive, see Is the LIKE operator case-sensitive with MS SQL server? for details. That's why Rec in Reclassify Hedge fits REC in the Like
_ (as well as %) is a wild card, you should escape _ in the pattern
Query:
SELECT remarks
FROM enroll
WHERE remarks LIKE 'REC*_%' ESCAPE '*' /* SQL 92 standard */
http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt
uses the triadic operator LIKE (or the inverse, NOT
LIKE), operating on three character strings and returning a Boolean.
LIKE determines whether or not a character string "matches" a given
"pattern" (also a character string). The characters '%' (percent)
and '_' (underscore) have special meaning when they occur in the
pattern. The optional third argument is a character string
containing exactly one character, known as the "escape character", for
use when a percent or underscore is required in the pattern without
its special meaning.

Related

Semicolon in LIKE is not working for SQL server 2017

I have a query like this which is not retrieving the values from DB table even if the required value exist there.
Here's the query, which return zero rows:
Select * from SitePanel_FieldValue WHere SiteFieldIdfk =111
And SiteFieldvalue like '%!##$%&*()-_=+{}|:"<>?[]\;'',./%'
Following is the value in the table:
'!##$%&*()-_=+{}|:"<>?[]\;'',./'
When I run the query without ";" it is returning the value.
Can any one help me in figuring this out?
Thanks
Ritu
You are using multiple characters which are reserved when using LIKE statement.
i.e. %, _, []
Use the escape character clause (where I have used backtick to treat special characters as regular) such as
Select * from SitePanel_FieldValue WHere SiteFieldIdfk =111
And SiteFieldvalue like '%!##$`%&*()-`_=+{}|:"<>?`[`]\;'',./%' escape '`'
The value in your table is:
!##$%&*()-_=+{};; :"<>?[]\;'',./
And the one in the like is:
(!##$%&*()-_=+{};;
Starting with ( it will never match, also you should scape the percent (%) in the middle of the string like this:
Select *
FROM SitePanel_FieldValue
WHERE SiteFieldIdfk =111
AND SiteFieldvalue like '%!##$\%&*()-_=+{};;%' ESCAPE '\'
The problem is your brackets ([]), it has nothing to do with semicolons. If we remove the brackets, the above works:
SELECT CASE WHEN '!##$%&*()-_=+{}|:"<>?\;'',./' LIKE '%!##$%&*()-_=+{}|:"<>?\;'',./%' THEN 1 END AS WithoutBrackets,
CASE WHEN '!##$%&*()-_=+{}|:"<>?[]\;'',./' LIKE '%!##$%&*()-_=+{}|:"<>?[]\;'',./%' THEN 1 END AS WithBrackets
Notice that WithoutBrackets returns 1, where as WithBrackets returns NULL.
Brackets in a LIKE are to denote a pattern. For example SomeExpress LIKE '[ABC]' would match the characters, A, B, and C. If you are going to include special characters, you need to ESCAPE them. You have both brackets, a percent sign (%) and an underscore (_) you need to escape. You don't need to escape the hyphen (-), as it doesn't appear in a pattern (for example [A-Z]). I choose to use a backtick as the ESCAPE character, as it doesn't appear in your string, and demonstrate with a CASE expression again:
SELECT CASE WHEN '!##$%&*()-_=+{}|:"<>?[]\;'',./' LIKE '%!##$`%&*()-`_=+{}|:"<>?`[`]\;'',./%' ESCAPE '`' THEN 1 END;
If you wanted to use a backslash (\ ), which many do, you would need to also escape the backslash in your string:
SELECT CASE WHEN '!##$\%&*()-_=+{}|:"<>?[]\;'',./' LIKE '%!##$%&*()-\_=+{}|:"<>?\[\]\\;'',./%' ESCAPE '\' THEN 1 END;
db<>fiddle
I think the issue is actually with the backslash. This is an escape character and so if you want it to be included, you have to put it in twice.
Select * from SitePanel_FieldValue WHere SiteFieldIdfk =111
And SiteFieldvalue like '%!##$%&*()-_=+{}|:"<>?[]\\;'',./%'

referencing a specific character out of a string in SQL Server

How do I reference only the second character in a column value with data type varchar(200) so that my SELECT * query will pull out only rows for which the second character is a space?
SQL Wildcard characters are:
%: zero or more characters
_: single character
You query should resemble SELECT * FROM x WHERE column LIKE '_ %'.
LIKE is a string operator that compares each character and suggests that your value should resemble (loosely defined) what follows.
'_ %' means:
Any single character, followed by
The space/white space character
Zero or more of any other character
The operator you are looking for is like. Try this:
select * from table_name where column_name like '_ %';
Here the _ leaves space for any one character, the second character has to be a ' ' and % means anything after that.
Hope this helps.

Where filename like '%_123456_%'

I'm trying to query a table with a like statement. Is _ considered a wildcard symbol in postgres? Would
select * from table where field1 like '%_123_%'
return the same thing as
select * from table where field1 like '%123%'
Here is an example from the official documentation regarding wildcards in Postgres:
'abc' LIKE 'abc' true
'abc' LIKE 'a%' true
'abc' LIKE '_b_' true
'abc' LIKE 'c' false
_ is a wildcard for one character, while % is a wildcard for multiple characters.
Yes, _ is a wildcard symbol that matches one character. It can't be an empty match, so no, those statements are not the same. The first requires the string be at least 5 characters long while the second only requires 3 characters.
If you're familiar with regexes, %123% is equivalent to .*123.*, while %_123_% is equivalent to .+123.+.
From the PostgreSQL manual:
To match a literal underscore or percent sign without matching other characters, the respective character in pattern must be preceded by the escape character. The default escape character is the backslash but a different one can be selected by using the ESCAPE clause. To match the escape character itself, write two escape characters.
yes
_ matches one char while % matches lots of chars.

in ms azure database how do you search for a string containing _

I have this situation on my azure database where I need to search for any rows that contains the _ character. This is a special character on the database so I try to escape it but I get every row as a result.
select * from table where fieldColumn like '%_%'
will return everything on the table
select * from table where fieldColumn like '%\_%'
returns nothing
select * from table where fieldColumn = '_'
works
so how can i get that row that has only one _ and all the other ones that may have the _ on the string?
You can set whatever escape character you want, like this:
select * from table where fieldColumn like '%!_%' ESCAPE '!'
Here I am using the ! as an escape character to tell SQL Server to treat the following character, the _ , as a string literal.
See the documentation for more info: http://technet.microsoft.com/en-us/library/ms179859.aspx
select * from table where fieldColumn like '%_%' escape '\';
LIKE:
escape_character
Is a character that is put in front of a wildcard character to indicate that the wildcard should be interpreted as a regular character and not as a wildcard. escape_character is a character expression that has no default and must evaluate to only one character.

List of special characters for SQL LIKE clause

What is the complete list of all special characters for a SQL (I'm interested in SQL Server but other's would be good too) LIKE clause?
E.g.
SELECT Name FROM Person WHERE Name LIKE '%Jon%'
SQL Server:
%
_
[specifier] E.g. [a-z]
[^specifier]
ESCAPE clause E.g. %30!%%' ESCAPE '!' will evaluate 30% as true
' characters need to be escaped with ' E.g. they're becomes they''re
MySQL:
% - Any string of zero or more characters.
_ - Any single character
ESCAPE clause E.g. %30!%%' ESCAPE '!' will evaluate 30% as true
Oracle:
% - Any string of zero or more characters.
_ - Any single character
ESCAPE clause E.g. %30!%%' ESCAPE '!' will evaluate 30% as true
Sybase
%
_
[specifier] E.g. [a-z]
[^specifier]
Progress:
% - Any string of zero or more characters.
_ - Any single character
Reference Guide here [PDF]
PostgreSQL:
% - Any string of zero or more characters.
_ - Any single character
ESCAPE clause E.g. %30!%%' ESCAPE '!' will evaluate 30% as true
ANSI SQL92:
%
_
An ESCAPE character only if specified.
PostgreSQL also has the SIMILAR TO operator which adds the following:
[specifier]
[^specifier]
| - either of two alternatives
* - repetition of the previous item zero or more times.
+ - repetition of the previous item one or more times.
() - group items together
The idea is to make this a community Wiki that can become a "One stop shop" for this.
For SQL Server, from http://msdn.microsoft.com/en-us/library/ms179859.aspx :
% Any string of zero or more characters.
WHERE title LIKE '%computer%' finds all book titles with the word 'computer' anywhere in the book title.
_ Any single character.
WHERE au_fname LIKE '_ean' finds all four-letter first names that end with ean (Dean, Sean, and so on).
[ ] Any single character within the specified range ([a-f]) or set ([abcdef]).
WHERE au_lname LIKE '[C-P]arsen' finds author last names ending with arsen and starting with any single character between C and P, for example Carsen, Larsen, Karsen, and so on. In range searches, the characters included in the range may vary depending on the sorting rules of the collation.
[^] Any single character not within the specified range ([^a-f]) or set ([^abcdef]).
WHERE au_lname LIKE 'de[^l]%' all author last names starting with de and where the following letter is not l.
ANSI SQL92:
%
_
an ESCAPE character only if specified.
It is disappointing that many databases do not stick to the standard rules and add extra characters, or incorrectly enable ESCAPE with a default value of ‘\’ when it is missing. Like we don't already have enough trouble with ‘\’!
It's impossible to write DBMS-independent code here, because you don't know what characters you're going to have to escape, and the standard says you can't escape things that don't need to be escaped. (See section 8.5/General Rules/3.a.ii.)
Thank you SQL! gnnn
You should add that you have to add an extra ' to escape an exising ' in SQL Server:
smith's -> smith''s
Sybase :
% : Matches any string of zero or more characters.
_ : Matches a single character.
[specifier] : Brackets enclose ranges or sets, such as [a-f]
or [abcdef].Specifier can take two forms:
rangespec1-rangespec2:
rangespec1 indicates the start of a range of characters.
- is a special character, indicating a range.
rangespec2 indicates the end of a range of characters.
set:
can be composed of any discrete set of values, in any
order, such as [a2bR].The range [a-f], and the
sets [abcdef] and [fcbdae] return the same
set of values.
Specifiers are case-sensitive.
[^specifier] : A caret (^) preceding a specifier indicates
non-inclusion. [^a-f] means "not in the range
a-f"; [^a2bR] means "not a, 2, b, or R."
Potential answer for SQL Server
Interesting I just ran a test using LinqPad with SQL Server which should be just running Linq to SQL underneath and it generates the following SQL statement.
Records
.Where(r => r.Name.Contains("lkjwer--_~[]"))
-- Region Parameters
DECLARE #p0 VarChar(1000) = '%lkjwer--~_~~~[]%'
-- EndRegion
SELECT [t0].[ID], [t0].[Name]
FROM [RECORDS] AS [t0]
WHERE [t0].[Name] LIKE #p0 ESCAPE '~'
So I haven't tested it yet but it looks like potentially the ESCAPE '~' keyword may allow for automatic escaping of a string for use within a like expression.