Skip to main content

Command Palette

Search for a command to run...

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

Published
1 min read

Context

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

Solution

In PostgreSQL, you can use cardinality to achieve this:

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

More from this blog

All about code - Ruby and Rails technical content written by Lucian Ghinda

101 posts

I write here quick thoughts, ideas, tips, and learnings about programming, programmers, and building software. Most of my focus is on Ruby, Rails, Hotwire, and everything about web applications.