Query several 'starts with' values in mySQL - mysql

I was trying to query values in a table where they started with 'a', 'b' or 'c'. I know in MS SQL you can make a [charlist] to do this:
( LIKE '[abc]%' )
I was wondering what the correct syntax was in other databases such as Oracle or mySQL.
Thanks

In MySQL you can use Regular Expressions
where some_column REGEXP '[abc].*'

MySQL follows the same syntax. Use % to wildcard, or ? single characters:
SELECT * FROM `table` WHERE `column` LIKE 'a%' OR `column` LIKE 'b%'...
Alternatively, You can use REGEXP in MySQL, but it will cause performance hits as you are unable to use indexes in order to query data.
For the SELECT LIKE 'a%' query it will be able to use the index to lookup all items starting with A, and return them efficiently. Using REGEXP will cause a row scan for each item, and performance will be greatly impacted.

Related

Regex bring just the match MySQL

I am trying to getting just the first two words on sql query, I am using the match: ^\w{2}- but with no success because nothing is coming to me, I need to get those values
BA, CE, DF, ES, GO, I don't know how can I do that, below some data example.
SC&Tipo=FM
SC&Tipo=Web
SC&Tipo=Comunitaria
RS&Tipo=Todas
RS&Tipo=AM
RS&Tipo=FM
RS&Tipo=Web
RS&Tipo=Comunitaria
BA-Salvador&Tipo=12horas
CE-Fortaleza&Tipo=12horas
CE-Interior&Tipo=12horas
DF-Brasilia&Tipo=12horas
ES-Interior&Tipo=12horas
ES-Vitoria&Tipo=12horas
GO-Goiania&Tipo=12horas
MG-ZonaDaMata/LestedeMinas&Tipo=12horas
MG-AltoParanaiba&Tipo=12horas
MG-BeloHorizonte&Tipo=12horas
MG-CentroOestedeMinas&Tipo=12horas
Query: SELECT * FROM tabel WHERE filter REGEXP '^\w{2}-'
EDIT SOLVED:
To solve the query should be:
SELECT SUBSTRING(column, 1, 2) AS column FROM table WHERE column REGEXP '^[[:alnum:]_]{2}-'
MySQL doesn't support the character class \w or \d. Instead of \w you have to use [[:alnum:]]. You can find all the supported character classes on the official MySQL documentation.
So you can use the following solution using REGEXP:
SELECT *
FROM table_name
WHERE filter REGEXP '^[[:alnum:]]{2}-'
You can use the following to get the result with regular expression too, using REGEXP_SUBSTR:
SELECT REGEXP_SUBSTR(filter, '^[[:alnum:]]{2}-')
FROM table_name
WHERE filter REGEXP '^[[:alnum:]]{2}-';
Or another solution using HAVING to filter the result:
SELECT REGEXP_SUBSTR(filter, '^[[:alnum:]]{2}-') AS colResult
FROM table_name
HAVING colResult IS NOT NULL;
To get the value before MySQL 8.0 you can use the following with LEFT:
SELECT LEFT(filter, 3)
FROM table_name
WHERE filter REGEXP '^[[:alnum:]]{2}-';
demo: https://www.db-fiddle.com/f/7mJEmCkEiYhCYK3PcEZTNE/0
Using SUBSTRING(<column>, 1, 2) should also work..
More or less like below
SELECT
<column>
, SUBSTRING(<column>, 1, 2)
FROM
<table>
WHERE
SUBSTRING(<column>, 1, 2) IN ('BA' [,<value>..])
Some things are BNF (Backus-Naur form) in the SQL code.
<..> means replace with what you need.
[, ..] means optional unlimited repeat the comma in there is part off SQL syntax

mysql query restricting on multiple periods

I'm trying to write a mysql query to detect three or more periods in a email string. Example
gr.em.test.t#domain.com
I'm thinking I could use some sort of mysql like query, but I'm not sure how to best write the regex. Any thoughts?
SELECT MyColumn
From MyTable
WHERE MyColumn like
No need for any type of regular expression, simply use the LIKE clause like you have, so you're on the right track. The following query should give you what you want:
SELECT MyColumn FROM MyTable WHERE MyColumn LIKE "%.%.%.%";

MySQL: Usage of 'REGEXP' instead of 'FIND_IN_SET'

I am having limitation in using MySQL's FIND_IN_SET function for searching array in set. Hence thinking of using of REGEXP. However can anyone help me constructing it.
E.g. My requirement
SELECT * FROM table AS t WHERE FIND_IN_SET('1,2,3', t.list);
Hence thinking of using REGEXP function to search array within set.
SELECT * FROM table AS t WHERE t.list REGEXP '1,2,3';
Can anyone help me building this REGEXP.
You can do like this:
SELECT * FROM table AS t WHERE t.list REGEXP '^9,|,9$|,9,' OR t.list =9
You can split your search string and continue to use FIND_IN_SET()
SELECT *
FROM `table` AS t
WHERE FIND_IN_SET('1', t.list)
AND FIND_IN_SET('2', t.list)
AND FIND_IN_SET('3', t.list)
Better yet normalize your data by introducing a many-to-many table.
For your requirements you can easily use:
SELECT *
FROM table1 AS t
WHERE t.list REGEXP '1|2|3';
To learn about regular expressions take look at this software:
http://www.weitz.de/regex-coach/
try the fallowing sql statement:
SELECT *
FROM table AS t
WHERE t.list REGEXP '^(1$|2$|3$)';

SQL SELECT LIKE (Insensitive casing)

I am trying to execute the sql query:
select * from table where column like '%value%';
But the data is saved as 'Value' ( V is capital ).
When I execute this query i don't get any rows.
How do i make the call such that, it looks for 'value' irrespective of the casing of the characters ?
use LOWER Function in both (column and search word(s)). Doing it so, you assure that the even if in the query is something like %VaLuE%, it wont matter
select qt.*
from query_table qt
where LOWER(column_name) LIKE LOWER('%vAlUe%');
If you want this column be case insensitive :
ALTER TABLE `schema`.`table`
CHANGE COLUMN `column` `column` TEXT CHARACTER SET 'utf8' COLLATE 'utf8_general_ci';
Thus, you don't have to change your query.
And the MySQL engine will process your query quicker than using lower() function or any other tricks.
And I'm not sure that using lower function will be a good solution for index searching performance.
Either use a case-insensitive collation on your table, or force the values to be lower case, e.g.
WHERE lower(column) LIKE lower('%value%');
Try using a case insensitive collation
select * from table
where column like '%value%' collate utf8_general_ci
Use the lower() function:
select t.*
from table t
where lower(column) like '%value%';
you should use either lower or upper function to ignore the case while you are searching for some field using like.
select * from student where upper(sname) like 'S%';
OR
select * from student where lower(sname) like 'S%';
If you are using PostgreSQL, a simpler solution is to use insensitive like (ILIKE):
SELECT * FROM table WHERE column ILIKE '%value%'
I know this is a very old question, but I'm posting this for posterity:
Non-binary string comparisons (including LIKE) are case-insensitive by default in MySql:
https://dev.mysql.com/doc/refman/en/case-sensitivity.html
This will eventually do the same thing. The ILIKE works, irrespective of the casing nature
SELECT *
FROM table
WHERE column_name ILIKE "%value%"

What is an efficient way to do pattern match in MySQL?

We have a huge pattern match in a query (about 12 strings to check).
Now I have to do this query in MySQL, but it seems that the query from PostgreSQL has not the same syntax.
From PostgreSQL:
SELECT value
FROM ...
WHERE ...
AND `value` !~* '.*(text|text2|text3|text4|text5).*';
How do I do this in MySQL in a efficient way? I know, that this is probably not efficient at all. What is the most efficient way to do this?
This does the trick, but is probably the worst query possible to do this:
SELECT `value`
FROM ...
WHERE ...
AND NOT (
`value` LIKE '%text%'
OR `value` LIKE '%text2%'
OR `value` LIKE '%text3%'
OR `value` LIKE '%text4%'
OR `value` LIKE '%text5%');
Is REGEXP the way to go here? Then I'll have to figure out the corresponding expression.
Yes, REGEXP or its alternative spelling RLIKE:
WHERE value NOT RLIKE 'text|text2|text3|text4|text5'
(a regexp match is not anchored to the ends of the string unless you explicitly use ^ and $, so you don't need the .*(...).*.)
You should test it to see whether it is actually faster than the version with LIKE. On my test database with four words to find, LIKE was still considerably faster. It also has the advantage of being ANSI standard SQL so you can use it on any database.
If this is a common query, you should also consider fulltext indexing.