Last Updated: February 25, 2016
·
2.643K
· mhenrixon

How to perform a group count on a postgresql array column

So you've heard about the array column in postgresql? Did you know that it's already possible to make good use of it?

All you need to do is go to https://github.com/dockyard/postgres_ext and follow the instructions to create a tags column for your rails model. Basically just a text field that will be treated as an array by postgresql and postgres_ext will help convert that into a regular string array in ruby.

Finding out how many records are tagged with something is easy enough but doing a group count is not as straight forward for a ruby developer. The below query does just that without having to join 3 different tables in the process.

explain analyze
with tags as (
  select unnest(tags) as tag_name from tasks where user_id = 1
) select 
    count(9), 
    tag_name
  from 
    tags
  group by
    tag_name