Regex for MySQL query - mysql

I am trying to select a field based on it meeting one of 3 criteria... and I'm not sure how to do this. I think a RegExp is probably the best method buy I'm unfamiliar with writing them.
Say I have the integer 123, I would like to match the following cases:
123 (thats 123 only with no spaces or other numbers after it)
123-10/12/2007 00:00 (thats 123 with a hyphen and a date, or actually it could be anything after the hyphen)
123_1014859 (thats 123 with an underscore, or again anything after the underscore)
Is there a way to do this using MySQL?

A regex is plausible, but it's not the best performing option. The last comparison put MySQL's regex support as being par with wildcarding the left side of a LIKE statement -- works, but the slowest of every option available.
Based on your example, you could use:
SELECT t.*
FROM YOUR_TABLE t
WHERE t.column LIKE '123-%'
OR t.column LIKE '123_%'
Another alternative, because OR can be a performance issue too, would be to use a UNION:
SELECT a.*
FROM YOUR_TABLE a
WHERE a.column LIKE '123-%'
UNION ALL
SELECT b.*
FROM YOUR_TABLE b
WHERE b.column LIKE '123_%'
UNION ALL will return all results from both tables; UNION removes duplicates, and is slower than UNION ALL for that fact.

select * from foo where bar regexp '^123-|_'
(not tested)

I would avoid using regex inside a SQL statement. Someone can correct me if I am wrong, but MySQL has to use another engine to run the regex.
SELECT * FROM table
WHERE field like "123"
OR field LIKE "123-%"
OR field like "123_%";

Related

Can anyone tell me in mysql How to display employee names whose name DO NOT start with alphabet A?

I am a beginner so please help me.
There are 2 things you need to combine in this case.
Because you didn't provide enough information in your question we have to guess what you mean by name. I'm going to assume that you have a single name column, but that would be unusual.
With strings, to match a character column that is not an exact match, you need to use LIKE which allows for wildcards.
You also need to negate the match, or in other words show things that are NOT (something).
First to match names that START with 'A'.
SELECT * FROM table_name WHERE name LIKE 'A%';
This should get you all the PEOPLE who have names that "Start with A".
Some databases are case sensitive. I'm not going to deal with that issue. If you were using MySQL that is not an issue. Case sensitivity is not universal. In some RDBMS like Oracle you have to take some steps to deal with mixed case in a column.
Now to deal with what you actually want, which is NOT (starting with A).
SELECT * FROM table_name WHERE name NOT LIKE 'A%';
your question should have more detail however you can use the substr function
SELECT name FROM yourtable
WHERE SUBSTR(name,1,1) <> 'A'
complete list of mysql string functions here
mysql docs
NOT REGXP operator
MySQL NOT REGXP is used to perform a pattern match of a string expression expr against a pattern pat. The pattern can be an extended regular expression.
Syntax:
expr NOT REGEXP pat
Query:
SELECT * FROM emp_table WHERE emp_name NOT REGEXP '^[a]';
or
SELECT * FROM emp_table WHERE emp_name NOT REGEXP '^a';

Count(1) and the Like statement Best use/Performance

Is there a better way of doing the below sql query I am not sure if the Like statement is the best option as the location column only contains exact matches.
INSERT INTO test_reports (Table_Name, Total_Count)
SELECT "table1", COUNT(1)
FROM table1
WHERE location LIKE 'birmingham'
There's no wildcards in your search string. Without wildcards, like is exactly the same as =.

MySQL multiple IN clause does not work

I have a MySQL table column rubrics which contains string value '61,80,112,256'. So I try execute that query:
select * from table where 256 in (rubrics) and 61 in (rubrics)
And no result returns. Any suggestions?
Since your rubrics column is a comma separated list the IN operator will not work.
MySQL does have a function that can find a value in a string list so you should be able to use FIND_IN_SET():
select *
from yourtable
where find_in_set(61, rubrics)
or find_in_set(256, rubrics)
See SQL Fiddle with Demo
Something like WHERE rubrics LIKE '%,256,%' OR rubrics LIKE '256,%' OR rubrics LIKE '%,256'. Using parenthesis you can also filter on the 61, but the resulting query will be come messy. You'd better normalize your data, so you can use subqueries and joins using keys (the real deal).
(see also bluefeet's answer as FIND_IN_SET is a better approach)
Try this
select * from table where rubrics like '%'+'256,'+'%' and rubrics like '%'+'61,'+'%'
IN operator does not work with strings
use correct substring matching operator like LIKE or LOCATE
one advice - update your rubics column to begin and end with , character, that will make your LOCATE(",62,", rubics) operations unambiguous as opposed to LOCATE("62", rubics) which will match also 622 and 262 and other combinations. Locating ,62, wil fail if your rubics has value of 62,blah,foo,bar because it doesn't start with ,

SQL string matching

I use a string for store the days of the week, something like this:
MTWTFSS. And if I search for MF (Monday and Friday) then the query must return all the strings that contain MF (for example: MWF, MTWTFS, MF, and so on).
I don't know how to do this in SQL (MySQL).
use LIKE with %-wildcard between the single characters:
SELECT * FROM table WHERE column LIKE '%M%F%';
note that this will only work if the characters are in correct order - searching for FM instead of MF won't give you any result.
you'll also need to find a way to insert the %s to your search-term, but taht shouldn't be a big problem (sadly you havn't said wich programming-language you're using).
if the characters can be in random order, you'll have to built a query like:
SELECT * FROM table WHERE
column LIKE '%M%'
AND
column LIKE '%F%'
[more ANDs per character];
SELECT * FROM yourTable WHERE columnName LIKE '%MF%'
Learn more:
http://www.sqllike.com/
Can you not just say
SELECT * FROM blah WHERE weekday LIKE "%MF%"

Difference between LIKE and = in MYSQL?

What's the difference between
SELECT foo FROM bar WHERE foobar='$foo'
AND
SELECT foo FROM bar WHERE foobar LIKE'$foo'
= in SQL does exact matching.
LIKE does wildcard matching, using '%' as the multi-character match symbol and '_' as the single-character match symbol. '\' is the default escape character.
foobar = '$foo' and foobar LIKE '$foo' will behave the same, because neither string contains a wildcard.
foobar LIKE '%foo' will match anything ending in 'foo'.
LIKE also has an ESCAPE clause so you can set an escape character. This will let you match literal '%' or '_' within the string. You can also do NOT LIKE.
The MySQL site has documentation on the LIKE operator. The syntax is
expression [NOT] LIKE pattern [ESCAPE 'escape']
LIKE can do wildcard matching:
SELECT foo FROM bar WHERE foobar LIKE "Foo%"
If you don't need pattern matching, then use = instead of LIKE. It's faster and more secure. (You are using parameterized queries, right?)
Please bear in mind as well that MySQL will do castings dependent upon the situation: LIKE will perform string cast, whereas = will perform int cast. Considering the situation of:
(int) (vchar2)
id field1 field2
1 1 1
2 1 1,2
SELECT *
FROM test AS a
LEFT JOIN test AS b ON a.field1 LIKE b.field2
will produce
id field1 field2 id field1 field2
1 1 1 1 1 1
2 1 1,2 1 1 1
whereas
SELECT *
FROM test AS a
LEFT JOIN test AS b ON a.field1 = b.field2
will produce
id field1 field2 id field1 field2
1 1 1 1 1 1
1 1 1 2 1 1,2
2 1 1,2 1 1 1
2 1 1,2 2 1 1,2
According to the MYSQL Reference page, trailing spaces are significant in LIKE but not =, and you can use wildcards, % for any characters, and _ for exactly one character.
I think in term of speed = is faster than LIKE. As stated, = does an exact match and LIKE can use a wildcard if needed.
I always use = sign whenever I know the values of something. For example
select * from state where state='PA'
Then for likes I use things like:
select * from person where first_name like 'blah%' and last_name like 'blah%'
If you use Oracle Developers Tool, you can test it with Explain to determine the impact on the database.
The end result will be the same, but the query engine uses different logic to get to the answer. Generally, LIKE queries burn more cycles than "=" queries. But when no wildcard character is supplied, I'm not certain how the optimizer may treat that.
With the example in your question there is no difference.
But, like Jesse said you can do wildcard matching
SELECT foo FROM bar WHERE foobar LIKE "Foo%"
SELECT foo FROM bar WHERE foobar NOT LIKE "%Foo%"
More info:
http://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html
A little bit og google doesn't hurt...
A WHERE clause with equal sign (=) works fine if we want to do an exact match. But there may be a requirement where we want to filter out all the results where 'foobar' should contain "foo". This can be handled using SQL LIKE clause alongwith WHERE clause.
If SQL LIKE clause is used along with % characters then it will work like a wildcard.
SELECT foo FROM bar WHERE foobar LIKE'$foo%'
Without a % character LIKE clause is very similar to equal sign alongwith WHERE clause.
In your example, they are semantically equal and should return the same output.
However, LIKE will give you the ability of pattern matching with wildcards.
You should also note that = might give you a performance boost on some systems, so if you are for instance, searching for an exakt number, = would be the prefered method.
Looks very much like taken out from a PHP script. The intention was to pattern-match the contents of variable $foo against the foo database field, but I bet it was supposed to be written in double quotes, so the contents of $foo would be fed into the query.
As you put it, there is NO difference.
It could potentially be slower but I bet MySQL realises there are no wildcard characters in the search string, so it will not do LIKE patter-matching after all, so really, no difference.
In my case I find Like being faster than =
Like fetched a number of rows in 0.203 secs the first time then 0.140 secs
= returns fetched the same rows in 0.156 secs constantly
Take your choice
I found an important difference between LIKE and equal sign = !
Example: I have a table with a field "ID" (type: int(20) ) and a record that contains the value "123456789"
If I do:
SELECT ID FROM example WHERE ID = '123456789-100'
Record with ID = '123456789' is found (is an incorrect result)
If I do:
SELECT ID FROM example WHERE ID LIKE '123456789-100'
No record is found (this is correct)
So, at least for INTEGER-fields it seems an important difference...