How to count the number of occurrences of a character in an Oracle varchar value? How to count the number of occurrences of a character in an Oracle varchar value? oracle oracle

How to count the number of occurrences of a character in an Oracle varchar value?


Here you go:

select length('123-345-566') - length(replace('123-345-566','-',null)) from dual;

Technically, if the string you want to check contains only the character you want to count, the above query will return NULL; the following query will give the correct answer in all cases:

select coalesce(length('123-345-566') - length(replace('123-345-566','-',null)), length('123-345-566'), 0) from dual;

The final 0 in coalesce catches the case where you're counting in an empty string (i.e. NULL, because length(NULL) = NULL in ORACLE).


REGEXP_COUNT should do the trick:

select REGEXP_COUNT('123-345-566', '-') from dual;


Here's an idea: try replacing everything that is not a dash char with empty string. Then count how many dashes remained.

select length(regexp_replace('123-345-566', '[^-]', '')) from dual