0

Given a model User and a string array column device_ids, how can I query for all Users that have nulls as an element of this array column?

E.g., some of the users has invalid values for device_ids:

user.device_ids
=> [null, "XYZABCDEFGH"]

I tried querying as suggested in this answer...

User.where.not("(-1 = ANY(device_ids)) IS NULL")

... but I get this error:

ERROR:  operator does not exist: integer = character varying

Is there any other ways to get all the users in a single query?

2
  • 1
    As far as SQL goes you can use something like EXISTS (SELECT * FROM unnest(device_ids) a(e) WHERE e IS NULL). (But I have no idea how to write that in for Rails.) But I advise against using arrays, if you cannot handle them atomically, i.e. you need to query single elements of them. Using the relational way is far less stressful. Commented Jun 17, 2021 at 23:05
  • thank you so much @stickybit! This helped me a lot. The only reason I'm querying single elements is because I need to remove the invalid ones. Commented Jun 17, 2021 at 23:31

1 Answer 1

0

Thank you for the help @sticky bit! My final solution was:

User.where("EXISTS (SELECT * FROM unnest(device_ids) a(e) WHERE e IS NULL)")

Sign up to request clarification or add additional context in comments.

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.