Lucian Ghinda
Random Thoughts about Building Software

Random Thoughts about Building Software

Active Record: How to select rows based on the number of items in an array column (PostgreSQL)

Lucian Ghinda's photo
Lucian Ghinda
·Dec 16, 2021·

1 min read

Subscribe to my newsletter and never miss my upcoming articles


You have a column in your table that is used as an array , like this:

 t.string 'ids', array: true

And you want to select all records that have more than N elements in the array


In PostgreSQL, you can use cardinality to achieve this:

Model.where("cardinality(ids) > 5")
Share this