4

I have got DB with IDs: 1 2 3 4 5. I need to return elements that exists in my array (simple list of data that usually specifying in IN ( ... ) ), but DO NOT exits in DB. For example checking values: 1, 2, 3, 4, 5, 6, 7.

So query should return 6, 7. How can I do it's with PostgreSQL?

1
  • 1
    I don't understand the output. Also, when say "array" are you using Postgres arrays or do you just generally mean a collection of numbers? Commented Dec 8, 2017 at 13:43

3 Answers 3

7

This can be solved using except

select *
from unnest(array[1,2,3,4,5,6]) as t(id)
except
select id
from the_table

With some test data:

select *
from unnest(array[1,2,3,4,5,6]) as t(id)
except
select id
from (values (1), (2), (3), (4) ) as the_table(id)

returns

id
--
 5
 6
Sign up to request clarification or add additional context in comments.

Comments

0
with t (id) as (values (1),(2),(3),(4),(5))
select u.id
from
    t
    right join
    unnest(array[1,2,3,4,5,6,7]) u (id) on t.id = u.id
where t.id is null
;
 id 
----
  6
  7

Comments

-1

If you want a query that excludes all elements in a list you can use the NOT IN statement.

SELECT * FROM someTable WHERE id NOT IN (1, 2, 3, 4, 5);

In your case you can create the query from your array.

1 Comment

This will not show values that do not exist in the table

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.