Reputation: 9869
I have got DB with ID
s: 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?
Upvotes: 4
Views: 1285
Reputation: 125544
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
Upvotes: 0
Reputation:
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
Upvotes: 7
Reputation: 104
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.
Upvotes: -1