4

I am trying to search multiple columns in my Db using a regex. It works but using many and/or statments. I was wondering if it was possible to use something like this;

SELECT * FROM table REGEXP 'regex' IN (col1, col2, col3,.....)

This doesn't work, it was a guess at the syntax because I can't find anything similar by searching online. Is this a stupid idea or am I missing something very simple?

2
  • I think correct key word is REGEXP not REGEX Commented Dec 11, 2013 at 18:48
  • Fulltext search it is called. Commented Dec 11, 2013 at 18:52

2 Answers 2

7

If you want to regexp search a value in multiple columns then you can do:

SELECT * FROM table where CONCAT(col1, col2, col3) REGEXP 'search-pattern';
Sign up to request clarification or add additional context in comments.

2 Comments

OK, any idea of performance implications of using CONCAT()? isn't it a great deal slower? not an issue in this case but I'm here to learn!
Performance will depend upon how many columns are you trying to concat. Besides this is like finding a needle in haystack. So speed will vary a lot depending upon size of haystack. IMO this is still better than writing 10 conditions with OR if you have 10 columns to search for.
2

The syntax for MySQL REGEX comparison is

expr REGEXP pattern_string

You cannot use it with IN. You would have to do:

SELECT * FROM `table` WHERE
col1 REGEXP 'regex'
OR col2 REGEXP 'regex'
OR col3 REGEXP 'regex'

You could also use RLIKE -- they are synonyms.

1 Comment

Thanks, that's what I was doing It was just an idea!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.