Search code examples
pythonpostgresqlvariablesin-clause

How to pass IN or NOT IN clause as variable to postgresql query using python


How to pass IN OR NOT IN clause as variable to a query?

When I pass the variable in the query bellow I get :

SELECT * FROM table_name WHERE column_name 'IN' ('product', 'category')

which triger an error for the presence of quotes 'IN'

query_clause = 'IN' 
##query_clause could equal 'NOT IN'

cur = my_connection.cursor()
cur.execute("SELECT * FROM table_name WHERE column_name %s ('product', 'category')", (query_clause,))

Solution

  • Yes, that's expected. Use a boolean parameter instead:

    SELECT * FROM table_name
      WHERE (column_name IN ('product', 'category')) = %s
    

    You can then pass true or false into the parameter.