SQL 'LIKE' query using '%' where the search criteria contains '%' - sql

I have an SQL query as below.
Select * from table
where name like '%' + search_criteria + '%'
If search_criteria = 'abc', it will return data containing xxxabcxxxx which is fine.
But if my search_criteria = 'abc%', it will still return data containing xxxabcxxx, which should not be the case.
How do I handle this situation?

If you want a % symbol in search_criteria to be treated as a literal character rather than as a wildcard, escape it to [%]
... where name like '%' + replace(search_criteria, '%', '[%]') + '%'

Use an escape clause:
select *
from (select '123abc456' AS result from dual
union all
select '123abc%456' AS result from dual
)
WHERE result LIKE '%abc\%%' escape '\'
Result
123abc%456
You can set your escape character to whatever you want. In this case, the default '\'. The escaped '\%' becomes a literal, the second '%' is not escaped, so again wild card.
See List of special characters for SQL LIKE clause

The easiest solution is to dispense with "like" altogether:
Select *
from table
where charindex(search_criteria, name) > 0
I prefer charindex over like. Historically, it had better performance, but I'm not sure if it makes much of difference now.

To escape a character in sql you can use !:
EXAMPLE - USING ESCAPE CHARACTERS
It is important to understand how to "Escape Characters" when pattern matching. These examples deal specifically with escaping characters in Oracle.
Let's say you wanted to search for a % or a _ character in the SQL LIKE condition. You can do this using an Escape character.
Please note that you can only define an escape character as a single character (length of 1).
For example:
SELECT *
FROM suppliers
WHERE supplier_name LIKE '!%' escape '!';
This SQL LIKE condition example identifies the ! character as an escape character. This statement will return all suppliers whose name is %.
Here is another more complicated example using escape characters in the SQL LIKE condition.
SELECT *
FROM suppliers
WHERE supplier_name LIKE 'H%!%' escape '!';
This SQL LIKE condition example returns all suppliers whose name starts with H and ends in %. For example, it would return a value such as 'Hello%'.
You can also use the escape character with the _ character in the SQL LIKE condition.
For example:
SELECT *
FROM suppliers
WHERE supplier_name LIKE 'H%!_' escape '!';
This SQL LIKE condition example returns all suppliers whose name starts with H and ends in _ . For example, it would return a value such as 'Hello_'.
Reference: sql/like

Select * from table where name like search_criteria
if you are expecting the user to add their own wildcards...

You need to escape it: on many databases this is done by preceding it with backslash, \%.
So abc becomes abc\%.
Your programming language will have a database-specific function to do this for you. For example, PHP has mysql_escape_string() for the MySQL database.

Escape the percent sign \% to make it part of your comparison value.

May be this one help :)
DECLARE #SearchCriteria VARCHAR(25)
SET #SearchCriteria = 'employee'
IF CHARINDEX('%', #SearchCriteria) = 0
BEGIN
SET #SearchCriteria = '%' + #SearchCriteria + '%'
END
SELECT *
FROM Employee
WHERE Name LIKE #SearchCriteria

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 '%!##$%&*()-_=+{}|:"<>?[]\\;'',./%'

Search special characters from SQL table

Text = “World“ world ” <world <Word> ‘ word’ ‘ word“ word’ =1254.25 = 2545.58. 20%
Hey guys,
I need to search a word from a string which was saved in my db. The searching word contains special characters such as ""'!##$%^<>. Below is the sql select query used for the search.
select * from TABLE where TABLE.text like ('%'+ '“ World' +'%')
as a result some of the special character are not searched. Characters such as double quotation, single quotation are not searched from this. need assistance with solving this problem asap. thank you :)
These Special characters are Unicode characters, When ever dealing with these characters in sql server you have to tell sql server explicitly that there can be some unicode characters in the strings you are about to manipulate by prefixing your strings with N'String'
In your case you would write a query something like ....
select * from TABLE
where TABLE.text like N'%'+ N'“ World' + N'%'
you can use the ESCAPE clause and escape your parameter value. http://technet.microsoft.com/en-us/library/ms179859.aspx
so for example to search for a string containing the character %
select * from TABLE where TABLE.text like ('%'+ N'\%' +'%') ESCAPE '\'

Matching a String having '%' as a character

I want to match a String using Like operator. The challenge is having '%' as a character in my string.
i.e. Row1 : Column = CT%CNV!XYZABCD...
Row2 : Column = CTXXXCNV!XYZABCDE...
If I use "SELECT * FROM table WHERE Column like 'CT%CNV!%'. It doesn't consider '%' as a character and the statement returns both rows.
I need to return the first row only.
You shoud use escape keyword:
select *
from MyTable
where Column like 'CT\%CNV!XYZABCD%' escape '\'
here '\%' is treated as a plain symbol, while '%' is wild card one
You can use brackets to escape the percent sign :
SELECT * FROM table WHERE Column like 'CT[%]CNV!%'

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.

SQL statement with LIKE

I would like to select all records that have an underscore character in their 11th character,
so i try this:
SELECT * FROM "BOM_SUB_LEVEL" where TOP_CODE like '%%%%%%%%%%_%%%'
but this doesnt work as expected, can someone help?
Just use the "SUBSTRING" function :
SELECT * FROM "BOM_SUB_LEVEL" where SUBSTRING(TOP_CODE, 11, 1) = "_"
Marc
For a single character wildcard use _. For multiple characters wildcards, use %. To escape a "real" appearance of _, use \_ (thanks Bill!).
Try the following code:
SELECT * FROM "BOM_SUB_LEVEL" where TOP_CODE like '___________\_%'
To further elaborate following Dav's comment, note that '%%%' is exactly the same as '%', since by definition '%' covers multiple characters.
pervasive uses _ to match any single character and \_ to actually match an underscore.
so the select would be:
SELECT * FROM "BOM_SUB_LEVEL" where TOP_CODE like '___________\_%'
LIKE % can mean any number of characters, use LIKE _ to mean just one. Since you're looking for an underscore, you need to escape it with !.
SELECT * FROM BOM_SUB_LEVEL WHERE TOP_CODE LIKE '__________!_%'
The % is not a per character wildcard, its a beginning and end of string wild card.
i.e. if I want to find all rows that have "car" in them, I would do this:
Select * from myTable where myCol LIKE '%car%'
If I wanted just the rows that STARTED with car:
Select * from myTable where myCol LIKE 'car%'
and ended with car:
Select * from myTable where myCol LIKE '%car'
% is a wildcard and can replace an character, or combination of characters. Use ? instead which replaces a single character.
You can try something like: (play with the numbers, I don't have pervasive to test with)
SELECT *
FROM BOM_SUB_LEVEL
where SUBSTRING(TOP_CODE, 11,1) = '-'