- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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;
Output
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;
Output
This will produce the following output −
+----------------------------------------------------------------------------+ | LENGTH(Value) + 2 -LENGTH(REPLACE(CONCAT(',', Value, ','), ',10,', 'len')) | +----------------------------------------------------------------------------+ | 3 | +----------------------------------------------------------------------------+ 1 row in set (0.00 sec)
Advertisements