4

How can I query for all records with an empty array, using the Postgres array data type?

 create_table "users", force: :cascade do |t|
   t.string   "email", limit: 255, default: "",null: false
   t.string   "roles", default: [], array: true
 end

I want to query for all records with an empty roles array.

Tried User.where("roles @> ?", '{}') but that did not work (returned 0 records).

2
  • have you tried just compare to nil or []? Commented May 25, 2016 at 22:37
  • you did create a record right? Commented May 25, 2016 at 22:50

3 Answers 3

16

Here is the syntax you can use:

User.where("roles = '{}'")
Sign up to request clarification or add additional context in comments.

4 Comments

Shouldn't it be: User.where("roles = '[]'") ? Since @chrismanderson defined the default to be [] not {}.
@wuliwong that was indeed the case for me
Using curly braces should be the working solution following the Postgres Documentation: postgresql.org/docs/9.1/static/arrays.html
@wuliwong Does not work in postres 10. Gives error: PG::InvalidTextRepresentation: ERROR: malformed array literal: "[]" Example with curly braces work fine
3

You can also do: User.where(roles: [])

I'm using Rails 5.2 (although the syntax may have been introduced earlier). I realize this is an old question, but in case anyone finds it from a Google search (like me).

1 Comment

This approach did not work for me ('rails', '~> 5.2.0').
0

Try this:

where("roles = ?", '{null}')

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.