Search code examples
mysqlsql-like

Mysql Regexp character at any position AND at the first position


I search using 'VW' I need a mysql regexp pattern that finds just VOLKSWAGEN and NOT VOLKSWAGEN and VOLVO.

I try first:

SELECT title FROM brand WHERE title REGEXP '^[VW]' 

So I get all records with V at the first position.

I do not know how to combine the conditions V at the FIRST character and W at ANY position.

I try :

SELECT title FROM brand WHERE title REGEXP '^[VW]' AND title REGEXP '[VW]' 

And also tryied with Having clause

SELECT title FROM brand WHERE title REGEXP '[VW]' HAVING title REGEXP '^[VW]' 

I know we have separate alternatives would we have a kind of && condition for REGEXP ?

Thank´s in advance


Solution

  • You don't need a regexp for this. You can just use like:

    where title like 'V%W%'
    

    The advantage of like is that MySQL can use an index on title to partially satisfy this (because the patter starts with a constant).