Using Pyscopg2, how do I pass a Python list into an SQL statement using the ANY Operator?
Normal Working SQL reads (See SQL Fiddle):
SELECT * FROM student WHERE id NOT IN (3);
Using Psycopg2 as below:
Psycopg2: Query 1
The query below fails with psycopg2.ProgrammingError: syntax error at or near "ANY"
id_list = [2,3,4]
cursor.execute("SELECT * FROM student WHERE id NOT IN ANY(%s)) %(id_list);
Psycopg2: Query 2
The query below doesn't throw an error but it gives a wrong result because it doesn't exclude the IDs in the list. It behaves as if its an Equal To operator or to be specific like its an IN
statement while I want a NOT IN
id_list = [2,3,4]
cursor.execute("SELECT * FROM student WHERE id != ANY(%s)), (id_list,);
Also, in my search I've come across pyscopg2 extension SQL_IN. Can it be used in this situation? If so, how do I use it?
When you do
2
will be compared to all array items and if there is any to which2
is not equal it will evaluate totrue
.Use
not id = any(array[2,3,4])
Or
!= all
The
SQL_IN
adapter makes it possible to use theIN
operator by adapting a tuple, not a list (lists are adapted to PostgreSQL arrays). To make your query work you should write the code as follows: