5

I have a Post model with the column defined by the following migration:

add_column :posts, :comments, :jsonb, default: []

add_index :posts, :comments, using: :gin

I would like to know the query to run so that I have a count of all the Posts which have the default, empty array as comments.

3 Answers 3

13
Post.where("comments = '[]'").count
Sign up to request clarification or add additional context in comments.

Comments

1

You can do this by converting the json to string, and count the length. Empty json will return 2. This works for both {} and []. E.g. To return non empty comment

Post.where("length(comments::text) > 2").count

Comments

0

With Postgresql > 11, this is also a possible answer

Post.where('jsonb_array_length(comments) > 0')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.