I have an SQL statement, SELECT foo FROM bar WHERE id IN %s
. I have a list of integers, e.g. [1, 2, 3]
and I'd like this to get turned into a SQL statement that looks like SELECT foo FROM bar WHERE id IN (1, 2, 3)
.
I use SQLAlchemy Core for its connection pooling and for making some inserts with multiple VALUES
clauses easier to write and maintain. I prefer to write most of my queries in raw SQL.
To do this in Pyscopg2 I do cursor.execute('SELECT .. WHERE IN %s', (tuple(my_list),))
. I can't manage to make this work in SQLAlchemy, however.
engine.execute('SELECT ... WHERE IN %s', tuple(my_list))
raises an exception: TypeError: not all arguments converted during string formatting. This same exception is raised if I pass just the list, not wrapped in a tuple.
If I use named parameters like engine.execute('SELECT ... WHERE id IN :ids', ids=my_list)
I get a ProgrammingError
exception because SQLAlchemy creates incorrect SQL: SELECT * FROM foo WHERE id IN :ids
(it doesn't substitute the :ids value for my variable). This same exception is raised if I pass a tuple.
How can I use a WHERE IN()
clause using raw SQL in SQLAlchemy?