I have a table called phones with a column like this where items here are repeated
brand |
---|
Samsung |
Apple |
Hydrogen |
Nokia |
Itel |
Honor |
Huawei |
and I want to use either the LIKE keyword or the regular expression in MySQL to get result that returns only Hydrogen
and Honor
in the brand
column of the table. I have tried the following
select distinct brand from phones where brand like 'h%o%r';
but it returned only Honor
instead of both. I’m trying to write a query that starts with ‘H’ and can have letter ‘o’, ‘r’ and even ‘n’ if possible that take any position, not necessarily in order, as is the case with Hydrogen
and Honor
.
I also tried select distinct brand from phones where brand like 'h%(o|r)';
and it gave an empty set. Help is appreciated.
2
Answers
To retrieve all the rows from the
phones
table where thebrand
column contains the letters “H”, “o”, and “r” in any order, you can use multipleLIKE
operators combined with theAND
operator:This query uses the
LIKE
function of the%
wildcard character to find the row with the specified character in thebrand
column. TheAND
operation is used to ensure that all three conditions are satisfied.If your database system supports regular expressions, you can also use a
REGEXP
function with more complex regular expressions to achieve the same result. Here is an example query that uses theREGEXP
function to find rows where thebrand
column contains the letters “H”, “o” and “r” in any order:If I’m understanding the root of the question, you’d like to return only the records with Hydrogen or Honor as the brand. Is there a specific reason you need to use the LIKE operator? Sounds like you can do this a couple of ways:
select * from phones where brand IN (‘Hydrogen’,’Honor’)
select * from phones where (brand = ‘Hydrogen’ OR brand = ‘Honor’)
Let me know if these work!