SQL Query like Condition not working as expected - sql

I have a query in SQL Server and have values like that is enclosed in the quote. I am trying to filter the value which has CC_ somewhere in the string. In the query when I try to filter the values using %CC_%, it is still returning the values though it is not present in the string.
with a as (
Select '#IDESC("Account"),#IDESC("Period"),#IDESC("View"),#IDESC("Scenario"),#IDESC("Version"),#IDESC("Years"),#IDESC("Currency"),#IDESC("Product"),#IDESC("FX View"),#IDESC("Data_Type"),#IDESC("Entity"),#IDESC("Function"),#IDESC("Market"),#IDESC("Business_Unit"),#IDESC("Reporting_Unit")'
as val)
select * from a where val like '%CC_%'
Can experts please help?

To match literal underscore in a SQL Server LIKE expression, you may place it into square brackets:
SELECT * FROM a WHERE val LIKE '%CC[_]%';
Underscore _ in a LIKE expression literally means any single character, and % means zero or more characters.

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

How run Select Query with LIKE on thousands of rows

Newbie here. Been searching for hours now but I can seem to find the correct answer or properly phrase my search.
I have thousands of rows (orderids) that I want to put on an IN function, I have to run a LIKE at the same time on these values since the columns contains json and there's no dedicated table that only has the order_id value. I am running the query in BigQuery.
Sample Input:
ORD12345
ORD54376
Table I'm trying to Query: transactions_table
Query:
SELECT order_id, transaction_uuid,client_name
FROM transactions_table
WHERE JSON_VALUE(transactions_table,'$.ordernum') LIKE IN ('%ORD12345%','%ORD54376%')
Just doesn't work especially if I have thousands of rows.
Also, how do I add the order id that I am querying so that it appears under an order_id column in the query result?
Desired Output:
Option one
WITH transf as (Select order_id, transaction_uuid,client_name , JSON_VALUE(transactions_table,'$.ordernum') as o_num from transactions_table)
Select * from transf where o_num like '%ORD12345%' or o_num like '%ORD54376%'
Option two
split o_num by "-" as separator , create table of orders like (select 'ORD12345' as num
Union
Select 'ORD54376' aa num) and inner join it with transf.o_num
One method uses OR:
WHERE JSON_VALUE(transactions_table, '$.ordernum') LIKE IN '%ORD12345%' OR
JSON_VALUE(transactions_table, '$.ordernum') LIKE '%ORD54376%'
An alternative method uses regular expressions:
WHERE REGEXP_CONTAINS(JSON_VALUE(transactions_table, '$.ordernum'), 'ORD12345|ORD54376')
According to the documentation, here, the LIKE operator works as described:
Checks if the STRING in the first operand X matches a pattern
specified by the second operand Y. Expressions can contain these
characters:
A percent sign "%" matches any number of characters or
bytes.
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"\%".
Thus , the syntax would be like the following:
SELECT
order_id,
transaction_uuid,
client_name
FROM
transactions_table
WHERE
JSON_VALUE(transactions_table,
'$.ordernum') LIKE '%ORD12345%'
OR JSON_VALUE(transactions_table,
'$.ordernum') LIKE '%ORD54376%
Notice that we specify two conditions connected with the OR logical operator.
As a bonus information, when querying large datasets it is a good pratice to select only the columns you desire in your out output ( either in a Temp Table or final view) instead of using *, because BigQuery is columnar, one of the reasons it is faster.
As an alternative for using LIKE, you can use REGEXP_CONTAINS, according to the documentation:
Returns TRUE if value is a partial match for the regular expression, regex.
Using the following syntax:
REGEXP_CONTAINS(value, regex)
However, it will also work if instead of a regex expression you use a STRING between single/double quotes. In addition, you can use the pipe operator (|) to allow the searched components to be logically ordered, when you have more than expression to search, as follows:
where regexp_contains(email,"gary|test")
I hope if helps.

How to use an underscore character in a LIKE filter give me all the results from a column

I am trying to filter my sql query with a like condition using underscore in my where clause. However, when i am filtering i want all values with just TS_AW19 and not all values which include TS which is what my query is currently giving me. Could someone assist me with the correct syntax to use for my query below?
SELECT
date,
creative_name,
SUM(revenue)*2 as spend
FROM `crate-media-group-client-data.DV360_ALL.GGLDV360BM_CREATIVE_*`
WHERE advertiser LIKE '%Topshop/Topman%' AND creative_name LIKE '%TS_AW19%' AND date = '2019-09-20'
GROUP BY 1,2
ORDER by creative_name
Note: i am using big query syntax for this query
Underscore (and percent) has a special meaning when used with LIKE, and means a wildcard for any single character. To workaround this, from the BigQuery documentation for LIKE:
You can escape "\", "_", or "%" using two backslashes. For example, "\%". If you are using raw strings, only a single backslash is required. For example, r"\%".
You may try double-escaping the underscore, if you intend for it be literal in your LIKE expression:
SELECT
date,
creative_name,
SUM(revenue)*2 AS spend
FROM `crate-media-group-client-data.DV360_ALL.GGLDV360BM_CREATIVE_*`
WHERE
advertiser LIKE '%Topshop/Topman%' AND
creative_name LIKE '%TS\\_AW19%' AND
date = '2019-09-20'
GROUP BY 1,2
ORDER BY
creative_name;

What does the trim function mean in this context?

Database I'm using: https://uploadfiles.io/72wph
select acnum, field.fieldnum, title, descrip
from field, interest
where field.fieldnum=interest.fieldnum and trim(ID) like 'B.1._';
What will the output be from the above query?
Does trim(ID) like 'B.1._' mean that it will only select items from B.1._ column?
trim removes spaces at the beginning and end.
"_" would allow representing any character. Hence query select any row that starts with "B.1."
For eg.
'B.1.0'
'B.1.9'
'B.1.A'
'B.1.Z'
etc
Optional Wildcard characters allowed in like are % (percent) and _ (underscore).
A % matches any string with zero or more characters.
An _ matches any single character.
I don't know about the DB you are using but trim usually remove spaces around the argument you give to it.
The ID is trimmed to be sure to compare the ID without any white-space around it.
About your second question, Only the ROWS with an ID like 'B.1.' will be selected.
SQL like
SQL WHERE

How to escape square bracket when using LIKE? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
SQL Server LIKE containing bracket characters
I am having a problem with pattern matching.I have created two objects say,with codes
1)[blah1]
2)[blah2] respectively
in the search tab,suppose if i give "[blah" as the pattern,its returning all the strings
i.e., [blah1] and [blah2]
The query is
select *
from table1
where code like N'%[blah%'
I guess the problem is with the condition and special characters. Please do revert if you have as solution. Is there any solution where we can escape the character"[". I tried to change the condition as N'%[[blah%'.But even then its returning all the objects that is in the table.
When you don't close the square bracket, the result is not specified.
However, the story is different when you close the bracket, i.e.
select *
from table1
where code like N'%[blah%]%'
In this case, it becomes a match for (any) + any of ('b','l','a','h','%') + (any). For SQL Server, you can escape characters using the ESCAPE clause.
select * from table1 where code like N'%\[blah%\]%' escape '\'
SQL Fiddle with examples
You can escape a literal bracket character this way:
select *
from table1
where code like N'%[[]blah%'
Source: LIKE (Transact-SQL), under the section "Using Wildcard Characters As Literals."
I guess this is Microsoft's way of being consistent, since they use brackets to delimit table and column identifiers too. But the use of brackets is not standard SQL. For that matter, bracket as a metacharacter in LIKE patterns is not standard SQL either, so it's not necessary to escape it at all in other brands of database.
As per My understanding, the symbol '[', there is no effect in query. like if you query with symbol and without symbol it shows same result.
Either you can skip the unwanted character at UI Level.
select * from table1 where code like '%[blah%'
select * from table1 where code like '%blah%'
Both shows same result.