Search code examples
pythonsqlpyathena

Pyathena SQL Query with Python condition


The following python list is given:

customer_list = [123,567,494]

Now I want to run a SQL query in which I use the list from above. How can I add the condition in (customer_list) to my query?

I tried:

my_query = """
select * from my_table
where customer in ("""+customer_list")" 
"""
order by name
"""

which gives me the error: TypeError: bad operand type for unary +: 'str'


Solution

  • you could try something like :

    customer_list = [123,567,494]
    
    my_query = """
    select * from my_table
    where customer in ({cust_list}) 
    order by name
    """.format(cust_list=",".join(str(x) for x in customer_list))
    

    Output:

    select * from my_table where customer in (123,567,494) order by name