0

I'm trying to write a simple query with the array function in PostgreSQL, but it doesn't seem to be working properly.

WITH vars AS (
  SELECT array['1114156957', '1234'] as npi
)
SELECT CASE 
         when '1114156957' <> ANY(npi) then 'Not Found'
         ELSE 'found'
       End as test
FROM vars;

I'm new to Postgres and have never used the array function before. But in the above query shouldn't the result be "Found" since one of values exists in the array?

0

1 Answer 1

3

'1114156957' <> ANY(..) means: "'1114156957' is not equal to any of the values in the array. Or to put it the other way round: "is not equal to at least one element in the array".

As there is one value that indeed is not equal, the condition '1114156957' <> ANY(npi) is true.

If you want to check if an element is not contained at all in the array, you need to use <> ALL()

WITH vars(npi) AS (
   values (array['1114156957', '1234'])
)
SELECT CASE 
         when '1114156957' = ALL(npi) then 'Not Found'
         ELSE 'found'
       End as test
FROM vars;

returns 'Found'

Online example: http://rextester.com/UDBNH6876

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.