Pyathena SQL Query with Python condition

351 Views Asked by At

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'

2

There are 2 best solutions below

0
On BEST ANSWER

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
0
On

You can relpace customer_list in your query with :

', '.join(str(element) for element in customer_list)