patternsqlCritical
Find IDs from a list that don't exist in a table
Viewed 0 times
idsexistthatfindlistfromtabledon
Problem
Say I have the following schema and data:
I want to perform a query like:
But this doesn't work. The case above should return
create table images(
id int not null
);
insert into images values(1), (2), (3), (4), (6), (8);I want to perform a query like:
select id from images where id not exists in(4, 5, 6);But this doesn't work. The case above should return
5, since it doesn't exist in the table records.Solution
You can use an outer join against a
or a
If you like you can also put the
values list (similar to Martin's answer mentioned above):select t.id
from (
values (4),(5),(6)
) as t(id)
left join images i on i.id = t.id
where i.id is null;or a
not exists together with the row constructor:select *
from (
values (4),(5),(6)
) as v(id)
where not exists (select *
from images i
where i.id = v.id);If you like you can also put the
values clause into a CTE to make the final query easier to read:with v (id) as (
values (4),(5),(6)
)
select v.id
from v
left join images i on i.id = v.id
where i.id is null;Code Snippets
select t.id
from (
values (4),(5),(6)
) as t(id)
left join images i on i.id = t.id
where i.id is null;select *
from (
values (4),(5),(6)
) as v(id)
where not exists (select *
from images i
where i.id = v.id);with v (id) as (
values (4),(5),(6)
)
select v.id
from v
left join images i on i.id = v.id
where i.id is null;Context
StackExchange Database Administrators Q#141129, answer score: 74
Revisions (0)
No revisions yet.