You get a bonus - 1 coin for daily activity. Now you have 1 coin

Counting specific characters in a MySQL column

Practice



To count the number of characters in a string (simply the character count), use the function:

CHAR_LENGTH(str)

for example:

SELECT CHAR_LENGTH(mycol) FROM mytable;


To count the number of certain characters (for example, delimiters) in a string, you'll need to write a query (for example, to count the number of ':' characters):

SELECT (CHAR_LENGTH(mycolumn) - CHAR_LENGTH(REPLACE(mycolumn,':',''))) div CHAR_LENGTH(':') FROM mytable;

That is, we:
a) Count the total number of characters
b) Replace the characters we need with nothing
c) Count the number of characters in the string without the ones we need to count
d) Since the "delimiter" could be a multibyte string - we count the length of the string
e) By dividing, we get the number of occurrences of the delimiter in the string


To calculate the maximum number of characters across all rows of a given column - add the MAX() function in front of the query above:

SELECT MAX((CHAR_LENGTH(mycolumn) - CHAR_LENGTH(REPLACE(mycolumn,':',''))) div CHAR_LENGTH(':')) FROM mytable;

Comments

Admin 15-07-2020
какая версия MySQL?
Admin 15-07-2020
работает
Admin 15-07-2020
(CHAR_LENGTH('mycolumn') - CHAR_LENGTH(REPLACE('mycoffflumn',':','' ))) div CHAR_LENGTH(':')
-3
Раскольникова 15-07-2020
SQL запрос: Документация
SELECT (CHAR_LENGTH(mycolumn) - CHAR_LENGTH(REPLACE(mycolumn,':',''))) div CHAR_LENGTH(':') FROM mytable;

Ответ MySQL: Документация
#1583 - Incorrect parameters in the call to native function 'CHAR_LENGTH'

To leave a comment

If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Lectures and tutorial on "Databases - MySql (Maria DB)"

Terms: Databases - MySql (Maria DB)