I'm using Postgres's native array type, and trying to find the records where the ID is not in the array recipient IDs.

I can find where they are IN:

SELECT COUNT(*) FROM "messages" WHERE (3 = ANY (recipient_ids))

But this doesn't work:

SELECT COUNT(*) FROM "messages" WHERE (3 != ANY (recipient_ids))
SELECT COUNT(*) FROM "messages" WHERE (3 = NOT ANY (recipient_ids))

what's the right way to test for this condition?

share|improve this question

68% accept rate
what is the error? – Janus Troelsen Jul 30 at 22:43
does WHERE 3 NOT IN recipient_ids work? – Janus Troelsen Jul 30 at 22:45
feedback

3 Answers

up vote 1 down vote accepted
  SELECT COUNT(*) FROM "messages" WHERE NOT (3 = ANY (recipient_ids))

You can always negate WHERE (condition) with WHERE NOT (condition)

share|improve this answer
feedback

You could turn it around a bit and say "3 is not equal to all the IDs":

where 3 != all (recipient_ids)

From the fine manual:

9.21.4. ALL (array)

expression operator ALL (array expression)

The right-hand side is a parenthesized expression, which must yield an array value. The left-hand expression is evaluated and compared to each element of the array using the given operator, which must yield a Boolean result. The result of ALL is "true" if all comparisons yield true (including the case where the array has zero elements). The result is "false" if any false result is found.

share|improve this answer
feedback

not (3 = any(recipient_ids)) ?

share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.