Mysql query - how to force sign "_" in pattern matching? - mysql

I have in database TEST these values for example:
ID
1_0
1_1
10_1
11_1
If I want select all values ​​at the beginning with number "1", but not "10" or "11" then I have created my request in that way:
SELECT * FROM test WHERE id LIKE '1_%';
But sign _ for Mysql Query also means one character from name so result of this will be all the values from the list.
My question is - how to force query to think that _ is a character in ID name, not sign of any letter?

I think you should be able to just escape the _ like so:
SELECT * FROM test WHERE id LIKE '1\_%';

Related

How to pull data that are in a specific pattern in MYSQL and PHP

I have a MySQL table and on of the column that contains username in different patterns. I am wondering is there a way to pull the usernames that (first 3 positions are in letter and last 4 positions are in number)? So I want to pull ABE0005, LKD0125, GHD0011, etc... See below for username examples.
username column:
ABE0005
LKD0125
905593580
GHD0011
903649229
BAN_SS_USER
This is how I pull data for username that starts with 9.
$query = mysqli_query($db, "SELECT * FROM `table_name` WHERE term = '2022' AND user LIKE '9%'");
$b_202310_3 = mysqli_num_rows($query);
Use regexp in a where clause to achieve this.
where username regexp '^[A-Z]{3}[0-9]{4}$'
^ is the start of the string
[A-Z] is any uppercase alpha character
{3} is 3 characters of the preceding group/class
[0-9] is any single integer
{4} is 4 of previous group/class
$ is the end of the string
Demo: https://regex101.com/r/LFFc4f/1 (Note this tool is using PCRE, MySQL uses POSIX (e.g. something like \d won't work in MySQL but would in this tool))
Per update query should be:
SELECT *
FROM `table_name`
WHERE term = '2022' AND user REGEXP '^[A-Z]{3}[0-9]{4}$'

How to find variable pattern in MySql with Regex?

I am trying to pull a product code from a long set of string formatted like a URL address. The pattern is always 3 letters followed by 3 or 4 numbers (ex. ???### or ???####). I have tried using REGEXP and LIKE syntax, but my results are off for both/I am not sure which operators to use.
The first select statement is close to trimming the URL to show just the code, but oftentimes will show a random string of numbers it may find in the URL string.
The second select statement is more rudimentary, but I am unsure which operators to use.
Which would be the quickest solution?
SELECT columnName, SUBSTR(columnName, LOCATE(columnName REGEXP "[^=\-][a-zA-Z]{3}[\d]{3,4}", columnName), LENGTH(columnName) - LOCATE(columnName REGEXP "[^=\-][a-zA-Z]{3}[\d]{3,4}", REVERSE(columnName))) AS extractedData FROM tableName
SELECT columnName FROM tableName WHERE columnName LIKE '%___###%' OR columnName LIKE '%___####%'
-- Will take a substring of this result as well
Example Data:
randomwebsite.com/3982356923abcd1ab?random_code=12480712_ABC_DEF_ANOTHER_CODE-xyz123&hello_world=us&etc_etc
In this case, the desired string is "xyz123" and the location of said pattern is variable based on each entry.
EDIT
SELECT column, LOCATE(column REGEXP "([a-zA-Z]{3}[0-9]{3,4}$)", column), SUBSTR(column, LOCATE(column REGEXP "([a-zA-Z]{3}[0-9]{3,4}$)", column), LENGTH(column) - LOCATE(column REGEXP "^.*[a-zA-Z]{3}[0-9]{3,4}", REVERSE(column))) AS extractData From mainTable
This expression is still not grabbing the right data, but I feel like it may get me closer.
I suggest using
REGEXP_SUBSTR(column, '(?<=[&?]random_code=[^&#]{0,256}-)[a-zA-Z]{3}[0-9]{3,4}(?![^&#])')
Details:
(?<=[&?]random_code=[^&#]{0,256}-) - immediately on the left, there must be & or &, random_code=, and then zero to 256 chars other than & and # followed with a - char
[a-zA-Z]{3} - three ASCII letters
[0-9]{3,4} - three to four ASCII digits
(?![^&#]) - that are followed either with &, # or end of string.
See the online demo:
WITH cte AS ( SELECT 'randomwebsite.com/3982356923abcd1ab?random_code=12480712_ABC_DEF_ANOTHER_CODE-xyz123&hello_world=us&etc_etc' val
UNION ALL
SELECT 'randomwebsite.com/3982356923abcd1ab?random_code=12480712_ABC_DEF_ANOTHER_CODE-xyz4567&hello_world=us&etc_etc'
UNION ALL
SELECT 'randomwebsite.com/3982356923abcd1ab?random_code=12480712_ABC_DEF_ANOTHER_CODE-xyz89&hello_world=us&etc_etc'
UNION ALL
SELECT 'randomwebsite.com/3982356923abcd1ab?random_code=12480712_ABC_DEF_ANOTHER_CODE-xyz00000&hello_world=us&etc_etc'
UNION ALL
SELECT 'randomwebsite.com/3982356923abcd1ab?random_code=12480712_ABC_DEF_ANOTHER_CODE-aaaaa11111&hello_world=us&etc_etc')
SELECT REGEXP_SUBSTR(val,'(?<=[&?]random_code=[^&#]{0,256}-)[a-zA-Z]{3}[0-9]{3,4}(?![^&#])') output
FROM cte
Output:
I'd make use of capture groups:
(?<=[=\-\\])([a-zA-Z]{3}[\d]{3,4})(?=[&])
I assume with [^=\-] you wanted to capture string with "-","\" or "=" in front but not include those chars in the result. To do that use "positive lookbehind" (?<=.
I also added a lookahead (?= for "&".
If you'd like to fidget more with regex I recommend RegExr

SQL SELECT statement with symbol or text

I am trying to get data from my database. I have no problems with this, the SELECT statement works fine, but I want to select the record with a symbor or text before the result.
When I run the code:
SELECT price
FROM products
WHERE id = "1"
Ill get 5.00. But in this case I want to select it with a "€" symbol before the price. I found some scripts on this site where they are using the following code:
SELECT "€ " + price as 'price'
FROM products
WHERE id="1"
When I run this i get the same result as in the first code. So my question is: How can I select the price from the database with a symbol or text before (or after) the result?
Since you specified what is your RDBMs your answer is:
SELECT CONCAT('€ ', price) as price
FROM products
WHERE id=1
Don't use double quotes to use strings, double quotes on SQL is to name things like columns as alias and only use it when you want a field named with characters that the database wouldn't allow it like "Column name with spaces"
Also, ID is probably a number, so no need to use quotes since it will imply in implicit conversion which will make your query slower.

Mysql SELECT all rows where char exists in value but not the last one

I need a SELECT query in MYSQL that will retrieve all rows in one table witch field values contain "?" char with one condition: the char is not the last character
Example:
ID Field
1 123??see
2 12?
3 45??78??
Returning rows would then be those from ID 1 and 3 that match the condition given
The only statement I have is:
SELECT *
FROM table
WHERE Field LIKE '%?%'
But, the MySQL query does not solve my problem..
The LIKE expressions also support a wildcard "_" which matches exactly one character.
So you can write an expression like the example below, and know that your "?" will not be the last character in the string. There must be at least one more character.
WHERE intrebare LIKE '%?_%'
Re comment from #JohnRuddell,
Yes, that's true, this will match the string "??" because a "?" exists in a position that is not the last character.
It depends whether the OP means for that to be a match or not. The OP says the string "45??78??" is a match, but it's not clear if they would intend that "4578??" to be a match.
An alternative is to use a regular expression, but this is a little more tricky because you have to escape a literal "?", so it won't be interpreted as a regexp metacharacter. Then also escape the escape character.
WHERE intrebare REGEXP '\\?[^?]'
you can just add an additional where where the last character is not a ?
SELECT *
FROM intrebari
WHERE intrebare LIKE '%?%' AND intrebare NOT LIKE '%?'
you could also do it like this
SELECT *
FROM intrebari
WHERE intrebare LIKE '%?%' AND RIGHT(intrebare,1) <> '?'
DEMO

Access query where criteria is Like Table1.Field but Field is a string type that contains "*"

I'm trying to create a select query in access where column Table2.FullNameField criteria is "Like Table1.ShortNameField". So the record is selected if Table2.FullNameField contains Table1.ShortNameField. Both fields are strings. The problem is the names contain an *. Here's an example:
ShortNameField = "A*01"
FullNameField = "A*01:04", "A*15:01", "A*03:02", etc
Query criteria = "Like Table1.ShortNameField" => Like A*01 (where * is interpreted as wild card)
The expected/desired result for the ShortNameField above would be to select the record with FullNameField of "A*01:04" but instead I'm getting the record with "A*15:01".
So the question is how do I get the Like function to treat the * in the short name as a character of the string and not a wildcard?
You might consider replacing the character:
SELECT t.shortnamefield, t.fullnamefield
FROM Table t
WHERE Replace([fullnamefield],"*","|")
Like "*" & Replace([shortnamefield],"*","|") & "*"
To escape special characters in LIKE clauses, the general rule is to enclose the character in [], e.g.[*] and [?].
Example:
select * from x where y like "[*]*"
will give you all records from table x where the y field starts with an asterisk (*).