From 6695f37cbb95efa4fd787ccee2c25f09dd16d88e Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Sat, 9 May 2015 11:43:18 -0500 Subject: [PATCH] Add Word Count for a Column as a postgres til. --- README.md | 1 + postgres/word-count-for-a-column.md | 21 +++++++++++++++++++++ 2 files changed, 22 insertions(+) create mode 100644 postgres/word-count-for-a-column.md diff --git a/README.md b/README.md index ccd5d4d..9698dc8 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,7 @@ smart people at [Hashrocket](http://hashrocket.com/). - [Timestamp Functions](postgres/timestamp-functions.md) - [Turning Timing On](postgres/turning-timing-on.md) +- [Word Count for a Column](postgres/word-count-for-a-column.md) ### rails diff --git a/postgres/word-count-for-a-column.md b/postgres/word-count-for-a-column.md new file mode 100644 index 0000000..11d0d9f --- /dev/null +++ b/postgres/word-count-for-a-column.md @@ -0,0 +1,21 @@ +# Word Count for a Column + +Assuming I have a database with a posts table: + +``` +> select * from posts where id = 1; + id | title | content +----+----------+------------------------------------ + 1 | My Title | This is the content of my article. +``` + +I can compute the word count of the content of a given post like so: + +``` +> select sum(array_length(regexp_split_to_array(content, '\s+'), 1)) from posts where id = 1; + sum +----- + 7 +``` + +[source](http://blog.lingohub.com/2013/07/sql-word-count-character-count-postgres/)