Finding number of occurrences of a specific string in MySQL?


Use LENGTH() for this. Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Value text
   -> );
Query OK, 0 rows affected (0.74 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('10,20,10,30,10,40,50,40');
Query OK, 1 row affected (0.24 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-------------------------+
| Value                   |
+-------------------------+
| 10,20,10,30,10,40,50,40 |
+-------------------------+
1 row in set (0.00 sec)

Following is the query to find number of occurrences of a specific string in MySQL. The occurrence of ‘10’ is what we are finding here −

mysql> select LENGTH(Value) + 2 -LENGTH(REPLACE(CONCAT(',', Value, ','), ',10,', 'len'))from DemoTable;

This will produce the following output −

+----------------------------------------------------------------------------+
| LENGTH(Value) + 2 -LENGTH(REPLACE(CONCAT(',', Value, ','), ',10,', 'len')) |
+----------------------------------------------------------------------------+
|                                                                          3 |
+----------------------------------------------------------------------------+
1 row in set (0.00 sec)
raja
Published on 11-Jul-2019 11:14:40
Advertisements