Search code examples
sqlpostgresqlleft-jointemp-tables

Postgres SQL: Find exceptions when using an in clause


I am running the following (Postgres) SQL against a table containing a list of ids. The SQL below will return all the ids found in the list* below.

select id from table
where id in (1,2,3,5,8,11,13,22,34,55);

How can I return ids which are contained in the list but not in the table? I realise I can do this using a temp table (with the list in it) and a left outer join but is there a quicker/cleverer way?


Solution

  • To check if arbitrary ids exist in your table, use a CTE and exists

    WITH ids (id) AS ( VALUES (1),(2),(3),(5),(8),(11),(13),(22),(34),(55)
    )
    SELECT id
    FROM ids 
    WHERE NOT EXISTS(SELECT TRUE FROM table WHERE table.id = ids.id)
    

    note1: alternatively use a left join instead of WHERE NOT EXISTS

    note2: it may be necessary to add the appropriate type casts

    Or you can use EXCEPT

    WITH ids (id) AS ( VALUES (1),(2),(3),(5),(8),(11),(13),(22),(34),(55)
    )
    SELECT id
    FROM ids 
    EXCEPT ALL 
    SELECT id FROM ids