Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - return ids from input that do not exist in database

Tags:

sql

postgresql

I am trying to write a query in postgresql that will do the follow: I want to give an array of ids, look them up in my database and ONLY return the ids (from the input) if there is no row associated with that id.

example: input: (1,2,3,4,5)

table:

id | name
---------
1    bobby
5    michael
6    amy
10   clare

output: 2,3,4

I am been looking into CASE, using NOT IN and just regular SELECTs but I can't seem to figure this one out.

Thanks in advance!

like image 788
Jerry Avatar asked Sep 10 '25 13:09

Jerry


1 Answers

Try this:

SELECT t1.v
FROM (VALUES (1), (2), (3), (4), (5)) t1(v)
LEFT JOIN mytable t2 ON t1.v = t2.id
WHERE t2.id IS NULL

Demo here

like image 72
Giorgos Betsos Avatar answered Sep 13 '25 06:09

Giorgos Betsos