Counting the number of occurrences of a character in a string can be useful in performing language processing and fuzzy searching. This tutorial will provide examples in SQL for different database engines.
The primary SQL function we will use in our query is LENGTH() (or LEN() on some systems). We first find the total number of characters in the string. We then remove all instances of the character that we are looking for from the string. By subtracting these two values we find the number of occurrences of the character we are looking for. The last step is to divide the result of our subtraction by the length of the character string we are searching for. This is only necessary if the character string has a length greater than one.
In this example, we are searching for the number of occurrences of the character ‘e’ in the column my_column. You may have to replace ‘length’ with ‘len’ on some database systems like SQL Server.