theChrisWalker.net

I’m sorry we’re out of Cake. We only had 3 pieces and didn’t expect the rush…

Archive for the ‘Regular Expressions’ tag

Regular Expressions in MySQL

without comments

I like regular expressions. Anyone who has tried to understand them will understand the learning curve involved and in no way do I claim to be an expert. However, I use them all the time. They are possibly the most useful thing I have ever learnt to do with programming and are more powerful I imagined at first.

So what does this have to do with MySQL?

Well, I was recently dealing wit a table in which there is some inline JSON serialised data. This makes sense for the situation but of course if you want to query on something within the data you have to be a bit more careful. You have two options as I saw it yesterday:

  • Pull all the data and parse it out outside of the database - which seems weak and inefficient.
  • Use some LIKE query to pull likely candidates and then parse out of the data base - again not so good, but a bit better.

The solution!

You can use Regular Expressions in a MySQL query! To simplify the problem I faced, suppose you have a field in the database which contains JSON data like this:

{ "content":[1,4,56,578,600,601], "next":56 }

And I want to find all records which contain a specific value in the “content” array (and suppose I know which records will have the “content” array by another field/method). LIKE would not be enough as it leaves to much room for error, but Regular Expressions - easy! If I want to find the value 578 then:

SELECT * FROM `table` WHERE `json_data` REGEXP '\\[([0-9]*,)*578(,|\\])';

Would find all records with 578 as an element in an array containing only numbers. Combine this with the method for restricting the SELECT to only filed you know will contain data in the right format and you have done it!

This is but one example, and the technique seems most useful when you have a serialised data format in your database field, but could be useful for advanced searching in table that do not support “fulltext” searches.

Written by Chris

January 23rd, 2009 at 9:40 am

Posted in Code

Tagged with ,