Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count items in comma separated list MySQL

Tags:

sql

mysql

So my question is pretty simple:

I have a column in SQL which is a comma separated list (ie cats,dogs,cows,) I need to count the number of items in it using only sql (so whatever my function is (lets call it fx for now) would work like this:

 SELECT fx(fooCommaDelimColumn) AS listCount FROM table WHERE id=... 

I know that that is flawed, but you get the idea (BTW if the value of fooCommaDelimColumn is cats,dogs,cows,, then listCount should return 4...).

That is all.

like image 369
Tomas Reimers Avatar asked Aug 11 '11 01:08

Tomas Reimers


People also ask

How do I count the number of comma separated values in MySQL?

Here LENGTH(column_name) - LENGTH(REPLACE(column_name, ',', '')) gives the number of commas in the value of each column. And +1 with this value provides the number of values separated by comma.

How do I SELECT comma separated values in MySQL?

In MySQL, you can return your query results as a comma separated list by using the GROUP_CONCAT() function. The GROUP_CONCAT() function was built specifically for the purpose of concatenating a query's result set into a list separated by either a comma, or a delimiter of your choice.

What is count (*) in MySQL?

MySQL COUNT() Function The COUNT() function returns the number of records returned by a select query.


1 Answers

There is no built-in function that counts occurences of substring in a string, but you can calculate the difference between the original string, and the same string without commas:

LENGTH(fooCommaDelimColumn) - LENGTH(REPLACE(fooCommaDelimColumn, ',', '')) 

It was edited multiple times over the course of almost 8 years now (wow!), so for sake of clarity: the query above does not need a + 1, because OPs data has an extra trailing comma.

While indeed, in general case for the string that looks like this: foo,bar,baz the correct expression would be

LENGTH(col) - LENGTH(REPLACE(col, ',', '')) + 1 
like image 91
zerkms Avatar answered Sep 22 '22 14:09

zerkms