Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I count the number of words in a string in Oracle?

I'm trying to count how many words there are in a string in SQL.

Select  ("Hello To Oracle") from dual;

I want to show the number of words. In the given example it would be 3 words though there could be more than one space between words.

like image 337
Dheya Majid Avatar asked Dec 23 '12 04:12

Dheya Majid


2 Answers

You can use something similar to this. This gets the length of the string, then substracts the length of the string with the spaces removed. By then adding the number one to that should give you the number of words:

Select length(yourCol) - length(replace(yourcol, ' ', '')) + 1 NumbofWords
from yourtable

See SQL Fiddle with Demo

If you use the following data:

CREATE TABLE yourtable
    (yourCol varchar2(15))
;

INSERT ALL 
    INTO yourtable (yourCol)
         VALUES ('Hello To Oracle')
    INTO yourtable (yourCol)
         VALUES ('oneword')
    INTO yourtable (yourCol)
         VALUES ('two words')
SELECT * FROM dual
;

And the query:

Select yourcol,
  length(yourCol) - length(replace(yourcol, ' ', '')) + 1 NumbofWords
from yourtable

The result is:

|         YOURCOL | NUMBOFWORDS |
---------------------------------
| Hello To Oracle |           3 |
|         oneword |           1 |
|       two words |           2 |
like image 115
Taryn Avatar answered Sep 30 '22 17:09

Taryn


Since you're using Oracle 11g it's even simpler-

select regexp_count(your_column, '[^ ]+') from your_table

Here is a sqlfiddle demo

like image 43
A.B.Cade Avatar answered Sep 30 '22 16:09

A.B.Cade