Count occurence of character (i.e. line breaks) in a MySQL field

November 8th, 2005

Unfortunately, there is no inbuilt MySQL function to count the occurance of a character in string. By counting the number of characters in the original string, then temporarily 'deleting' the character you want to count and counting the string again, subtracting the first count from the second, you get the number of occurances:

SELECT LENGTH('foobarfoobarfoobar') - LENGTH(REPLACE('foobarfoobarfoobar', 'b', '')) AS `occurances`
--> 3

Obviously, in this example 'b' is the string you want to count the number of occurances of.

You can use the same principle to count the number of lines in a field, by adding one to the difference:

SELECT LENGTH(`foo`) - LENGTH(REPLACE(`foo`, 'n', '')) + 1 AS `numLines` FROM `bar`

Maybe that'll save you some hunting around!


 Add to del.icio.us    Digg this    Technorati

Related Posts:

Entry Filed under: MySQL

1 Comment Add your own

  • 1. REB  |  February 8th, 2006 at 12:23 pm

    Great tip !
    Note that if you count word occurences (several charcters) you'll have to divide by the number of char :

    SELECT (LENGTH(strContent) - LENGTH(REPLACE(strContent, '$strWord', ''))) / LENGTH('$strWord') AS intOccurence

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


Calendar

November 2005
M T W T F S S
    Dec »
 123456
78910111213
14151617181920
21222324252627
282930  

Most Recent Posts