0

I have setup a PostgreSQL array field identical to this example on edgeguides. I am querying on these fields like:

Book.where("'fantasy' = ANY (tags)")

But what I need is to query the inverse of this; all records where tags does not include 'fantasy' (in this example).

Anyone have any guidance? I cannot find much documentation on working with a PostgreSQL array field outside of the aforementioned guide.

2 Answers 2

1

You can negate your condition

Book.where("NOT('fantasy' = ANY (tags))")

So you can modify query to get records with NULL records also:

Book.where("NOT('fantasy' = ANY (tags)) or tags IS NULL")

Also you can run these queries in psql and check results

SELECT * FROM book WHERE NOT('fantasy' = ANY (tags)); 
SELECT * FROM book WHERE NOT('fantasy' = ANY (tags)) OR tags IS NULL; 
SELECT * FROM book WHERE 'fantasy' = ANY (tags) 

Maybe there is no records without tag 'fantasy'?

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

6 Comments

That just returns no results unfortunately.
@TonyBeninate Try run these queries in psql SELECT * FROM book WHERE NOT('fantasy' = ANY (tags)); SELECT * FROM book WHERE 'fantasy' = ANY (tags) Maybe there is no records without tag 'fantasy'?
I was using the "book/fantasy" example as way of staying constant with the Edgeguides, that's not my actual data, I'm using archived_by which contains an array value; however, I have plenty records where the equivalent "tag" is blank: user.conversations.last(10).map(&:archived_by) => [nil, nil, nil, nil, nil, nil, nil, nil, nil, [359034]]
So you can modify query to get records with NULL records also: Book.where("NOT('fantasy' = ANY (tags)) or tags IS NULL")
SHOOT — I need to run some more testing but at first glance this appears to be working!
|
0

Try this:

Book.where.not('tags @> ARRAY[?]', "fantasy")

1 Comment

This is the approach I had been trying to get working myself, but for some reason this returns no results here.

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.