1

I want to search a column for all instances of a string

For example, if I have this a column with the value all good all bad all better I want to find the number of instances of all.

I tried

select instr(column, 'all') from test_table;

but that only returns the position of the first occurrence of all. I'm using Oracle 11g database.

Is there a way I can find all instances of a specific string in Oracle db?

VH-NZZ
  • 5,248
  • 4
  • 31
  • 47
  • first thing i thought of was the CHARINDEX function, but then I saw Oracle. I have only been working in Oracle for about a month now, but this might help you. http://nishantrana.wordpress.com/2007/10/03/using-left-and-charindex-in-oracle/ – mmeasor May 01 '14 at 20:31

3 Answers3

2
SELECT REGEXP_COUNT(column, 'all') AS Cnt
FROM test_table;
wvdz
  • 16,251
  • 4
  • 53
  • 90
  • Oracle has a regexp_count function (http://docs.oracle.com/cd/B28359_01/server.111/b28286/functions135.htm#SQLRF20014). If you're going to use a regular expression, you should be using that. – Justin Cave May 01 '14 at 20:51
2

Since you're on 11g, you can use the regexp_count function. If you want to do a case-sensitive count

SELECT regexp_count( column, 'all' )
  FROM table_name

If you want a case-insensitive count

SELECT regexp_count( column, 'all', 1, 'i' )
  FROM table_name
Justin Cave
  • 227,342
  • 24
  • 367
  • 384
0

This works with MySQL - have not tested with Oracle but I see no reason why it wouldn't work:

SELECT (LENGTH(column) - LENGTH(REPLACE(column, 'all', '')))/LENGTH('all') FROM table
Mark Miller
  • 7,442
  • 2
  • 16
  • 22