Jayamal Kulathunge
Jayamal Kulathunge

Reputation: 249

Pattern Matching Using SQL

I need to match bellow mentioned patterns using SQL.

  1. "* THANK YOU"
  2. "* MUSIC *"
  3. "I LIKE * MUSIC"
  4. "I LIKE * MUSIC AND * PAINTING"

Input strings will look like this,
"HI THANK YOU" -> should match "* THANK YOU"
"I LIKE MUSIC VERY MUCH" -> should match "* MUSIC *"

Is there a way to do this using standard SQL syntax.

Please help.

Thank you.

Upvotes: 1

Views: 1427

Answers (2)

AbsoluteƵERØ
AbsoluteƵERØ

Reputation: 7870

Oracle MySQL Sample Queries:

Case insensitive:

select * from database where column like '%THANK YOU%';

Case sensitive:

select * from database where column LIKE BINARY '%THANK YOU%';

Case insensitive:

select * from database where column REGEXP 'THANK YOU';

Oracle Queries:

select * from database WHERE REGEXP_LIKE(column, 'THANK YOU', 'i')

You can use LIKE in Oracle, but case insensitivity setup depends on the version.

Case sensitive:

select * from database WHERE column LIKE 'THANK YOU';

There is a lot of discussion about making Oracle's like case insensitive. It's easier to use the reg_exp version for that and set the i flag for case insensitivity.

Update The original question was actually opposite of my first answer, and it has really opened up my head about quite a few apps that I'm building for datamining. Actually had this idea last night but the original poster posted it before I did (Fiddle was down). You can make Regex match both sides of the REGEXP function in MySQL. So if you store a list of expressions into the database, then you can actually compare the list of expressions against a table of entries or a single string.

I've added an SQL Fiddle here: http://sqlfiddle.com/#!8/701a0/2

Note that in the original example, the "regex" values in the database started with just an asterisk. In Regex, the actual string would need to be .* for possibly any character.

I've added a few examples for matching things like websites, US Toll Free Numbers, and gmail accounts.

INSERT INTO `myRegex` VALUES (1,'.* THANK YOU$'),(2,'MUSIC'),(3,'I LIKE .* MUSIC'),(4,'I LIKE .* MUSIC AND .* PAINTING'),(5,'^[0-9]?[ .-]?(800|866)'),(6,'\\.com$'),(7,'\\.net$'),(8,'\\.(gmail|googlemail)\\.'),(9,'THANK YOU');

Output

select * from myRegex where 'HI THANK YOU' REGEXP reg_expr;

enter image description here

select * from myRegex where 'THANK YOU MUCH' REGEXP reg_expr;

enter image description here

Upvotes: 1

Jayamal Kulathunge
Jayamal Kulathunge

Reputation: 249

I found a way to do this using MySQL,

SELECT * FROM knowledge WHERE 'HI THANK YOU' REGEXP pattern_col;

pattern_col holds regexps.

Upvotes: 1

Related Questions