2

Is this possible in (Oracle) SQL?

I have a varchar for example "This is varchar" and I want to count number of "i" (it's 2)...

Nick Krasnov
  • 26,886
  • 6
  • 61
  • 78
FireVortex
  • 303
  • 3
  • 8
  • 16

3 Answers3

5

Try to use REGEXP_COUNT function as below:

select  REGEXP_COUNT( 'This is varchar', 'i' ) from dual

Here you can find more information about REGEXP_COUNT.

SQL Fiddle DEMO

Robert
  • 25,425
  • 8
  • 67
  • 81
  • Caveat: I'm not an Oracle developer. I'm sure this works very well for the example but I would take heed to the `REGEXP` part of function name; simply substituting in `'.'` in place of `'i'` might not do what one wants it to do. – ta.speot.is Nov 21 '12 at 13:05
  • @ta.speot.is but this `select REGEXP_COUNT( 'This is varchar.', '[.]' ) from dual` will work :) – Robert Nov 21 '12 at 13:06
3

You could remove all of the is and check the length difference.

select length('This is varchar')
       - NVL(length(replace('This is varchar', 'i')) , 0)
from dual;
Jeffrey Kemp
  • 59,135
  • 14
  • 106
  • 158
xdazz
  • 158,678
  • 38
  • 247
  • 274
1

Try this:

LENGTH(varcharString) - LENGTH(REPLACE(varcharString, 'i', ''))
Mahmoud Gamal
  • 78,257
  • 17
  • 139
  • 164