Query to count words SQLite 3 Query to count words SQLite 3 sqlite sqlite

Query to count words SQLite 3


As far as I know there is no way to directly count the number of words in a string in SQL lite 3. (I'm more familiar with mysql and ms sql)

You can use Length and Replace as a work around

 SELECT length(@String) - length(replace(@String, ' ', '')) + 1


The previous answer is incorrect for columns that are blank. You will need to add a case/when/then statement to your select:

SELECT someStr,  CASE WHEN length(someStr) >= 1  THEN    (length(someStr) - length(replace(someStr), ' ', '')) + 1  ELSE    (length(someStr) - length(replace(someStr), ' ', ''))  END as NumOfWordsFROM someTable;

Edited: If the column has 0 spaces, but had a word in it, it would incorrectly report 0. Changed the condition to allow for it.

Source: An Excel Trick I used to do the same thing


The answer from @Ziferius has a small syntax error, the following one is a working one, tested by myself.

SELECT someStr,   CASE WHEN length(someStr) >= 1   THEN     (length(someStr) - length(replace(someStr, ' ', ''))) + 1   ELSE     (length(someStr) - length(replace(someStr, ' ', '')))   END as NumOfWords FROM someTable;