Count the number of comma’s in every record from a comma-separated value column in MySQL


Let us first create a −

mysql> create table DemoTable1510
   -> (
   -> Value varchar(50)
   -> );
Query OK, 0 rows affected (6.75 sec)

Insert some records in the table using insert −

mysql> insert into DemoTable1510 values('20,35');
Query OK, 1 row affected (0.57 sec)
mysql> insert into DemoTable1510 values('45,67,89');
Query OK, 1 row affected (0.99 sec)
mysql> insert into DemoTable1510 values('90,97,101,190');
Query OK, 1 row affected (1.15 sec)

Display all records from the table using select −

mysql> select * from DemoTable1510;

This will produce the following output −

+---------------+
| Value         |
+---------------+
| 20,35         |
| 45,67,89      |
| 90,97,101,190 |
+---------------+
3 rows in set (0.00 sec)

Here is the query to count comma’s −

mysql> select length(Value) - length(replace(Value, ',', '')) as NumberOfComma from DemoTable1510;

This will produce the following output −

+---------------+
| NumberOfComma |
+---------------+
|             1 |
|             2 |
|             3 |
+---------------+
3 rows in set (0.00 sec)

Updated on: 12-Nov-2019

965 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements