Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I query for Strings containing a letter more than once?

Tags:

string

mysql

How do I run a query in MySQL to search for Strings containing a character on more than one occurrence?

SELECT * FROM animals WHERE name LIKE '%r%' will only return animals that contain an 'r'..

+---------+------------+
|    id   | name       |
+---------+------------+
|     1   | zebra      |
|     14  | raccoon    |
|     25  | parrot     | 
|     49  | rhinoceros |
+---------+------------+

SELECT * FROM animals WHERE name LIKE '%rr%' will only return animals that contain an occurance of 'rr'..

+---------+------------+
|    id   | name       |
+---------+------------+
|     25  | parrot     | 
+---------+------------+

I would like to find any animal names that contain an 'r'.. lets say twice anywhere in the name.

+---------+------------+
|    id   | name       |
+---------+------------+
|     25  | parrot     | 
|     49  | rhinoceros |
+---------+------------+

Anyone?

like image 869
ecirp Avatar asked Jun 23 '13 20:06

ecirp


People also ask

How do I select multiple values in SQL query?

To select multiple values, you can use where clause with OR and IN operator.

How do I match part of a string in SQL?

We can use LIKE Operator of SQL to search sub-string. The LIKE operator is used with the WHERE Clause to search a pattern in string of column. The LIKE operator is used in a conjunction with the two wildcards characters.

How can I get certain words from a string in SQL?

SQL Server SUBSTRING() Function The SUBSTRING() function extracts some characters from a string.


2 Answers

Have you tried this?

select *
from animals
where name like '%r%r%'

An alternative solution is to use length and replace:

select *
from animals
where length(name) - length(replace(name, 'r', '')) >= 2;

This could be advantageous if you were looking for occurrences of a set of letters, for instance 'r' and 's':

select *
from animals
where length(name) - length(replace(replace(name, 'r', ''), 's', '')) >= 2;

EDIT:

If you want exactly two "r"s, you can just use equality in the where clause:

select *
from animals
where length(name) - length(replace(name, 'r', '')) = 2;
like image 145
Gordon Linoff Avatar answered Sep 27 '22 21:09

Gordon Linoff


You can go about it indirectly, by checking how much a string's length changes when you REMOVE those characters:

SELECT id, name
FROM yourtable
WHERE (length(name) - length(replace(name, 'r', ''))) >= 2

e.g. parrot has 6 chars, and with the r removed, is only 4, so 6-4=2 and would match the where.

like image 21
Marc B Avatar answered Sep 27 '22 20:09

Marc B