[SOLVED] How to use variables in SQL statement in Python using IN statement

Issue

I have dataframe with 2 cols, id and email. Now I want to write sql query to use in python which dynamically fetches only those emails which are present in df['email'].
The sql equivalent of this query will be something like this

select id, email from xdb where email in (email1, email2, ...);

But I want something like df['email'] instead of (email1, email2, ...). How can I put a variable in place of writing all those email one by one?
And am using pandas pd.read_sql function to run the queries and mysql.

Solution

use:

pd.read_sql(f"select id, email from xdb where email in {tuple(df.email.values)}", conn)

Answered By – keramat

Answer Checked By – Mildred Charles (BugsFixing Admin)

Leave a Reply

Your email address will not be published.