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,363
  • 6
  • 58
  • 76
FireVortex
  • 293
  • 3
  • 7
  • 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
  • 24,847
  • 8
  • 64
  • 77
  • 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
  • 57,730
  • 14
  • 106
  • 150
xdazz
  • 154,648
  • 35
  • 237
  • 264
1

Try this:

LENGTH(varcharString) - LENGTH(REPLACE(varcharString, 'i', ''))
Mahmoud Gamal
  • 75,299
  • 16
  • 132
  • 159