SQL Tricks/Tip-How to find the number of times a character occurs in a string using SQL
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.
SELECT (length(my_column)-length(replace(my_column,'e','')))/length('e')as counterFROM my_table |
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.
Tags:
php sql,sql datepart,sql concatenate,excel courses online,sql escape character,sql truncate table,ansi sql,sql pivot,sql developer jobs,sql server free,sql select into,sql data types
sql reporting services,sql wildcard,advanced sql,in sql,sql client