Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting the number of occurrences of a character in Oracle SQL [closed]

How can I count the number of times that a particular character occurs in a column in Oracle? For example, if I have a table FOO that has data like a,ABC,def and 2,3,4,5, I want to count the number of times that a comma appears in the data.

CREATE TABLE foo (
  str varchar2(30)
);

INSERT INTO foo VALUES( 'a,ABC,def' );
INSERT INTO foo VALUES( '2,3,4,5' );
commit;

The output that I want is

str         cnt
a,ABC,def   2
2,3,4,5     3
like image 830
Sharath Avatar asked May 27 '12 06:05

Sharath


People also ask

How do you count the number of occurrences of a character in an Oracle?

The Oracle/PLSQL REGEXP_COUNT function counts the number of times that a pattern occurs in a string. This function, introduced in Oracle 11g, will allow you to count the number of times a substring occurs in a string using regular expression pattern matching.

How do I count the number of repeating characters in a string in Oracle?

To count how many occurrences of a character, say 'x' , exist in a string like 'zxxydds' , the fastest way is to use the string function REPLACE() to remove all the occurrences of 'x' from the string (by replacing 'x' with '' ), and then to subtract the length of the resulting string from the length of the original ...

How do I count how many times a word appears in SQL?

T-SQL doesn't provide a built-in function to count the number of times a particular string appears within another string, so to find out how many times a word appears in a row, you have to build your own count function. SQL Server 2000 lets you create this kind of user-defined function (UDF).


1 Answers

One of the usual tricks for this is to use a combination of length and replace:

select (length(your_col) - length(replace(your_col, ','))) from your_table;

replace without a third argument will simply remove the character.

like image 166
Mat Avatar answered Sep 25 '22 00:09

Mat