Find IDs from a list that don't exist in a table
You can use an outer join against a 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;
One way of doing it would be to use VALUES
to create a table expression with the ids to check and EXCEPT
to find the missing ones.
SELECT id
FROM (VALUES(4),(5),(6)) V(id)
EXCEPT
SELECT id
FROM images;
While using EXCEPT
like @Martin provided, remember to make it EXCEPT
ALL
, unless you want to pay a little extra for trying to fold duplicates.
BTW, a VALUES
expression can stand on its own:
VALUES (4),(5),(6)
EXCEPT ALL
SELECT id FROM images;
But you get default column names this way.
For a long list of values it may be more convenient to provide it as array and unnest. Shorter syntax:
SELECT * FROM unnest('{4,5,6}'::int[]) id
EXCEPT ALL
SELECT id FROM images;
There are a couple of basic techniques for the task:
- Select rows which are not present in other table