I am querying for ids using a for-loop. So multiple selects are being used. Is there a better way to do this to have a single select statement for all ids?

for id in aoi_ids:
    sql = """SELECT id, date, col3 FROM table1 WHERE id=%s"""
    params = [id] 

    return helper_func_to_execute_query(sql, params)

I know once way is to use another table. Any other faster way to do it?

1 Answer 1


If you can sanitize input, you can use an IN statement.

WHERE id IN ( 1,2,3 );

Or you can chain the WHERE clauses.

WHERE ID = 1 OR ID = 2;
  • IN is slower than creating a temp table. I was looking some other faster way besides these two. But anyways, thanks for your reply.
    – Atihska
    Feb 28, 2018 at 19:36
  • @Atihska - Basically, you have to get the ID values into SQL somehow, or pull all data and filter on the app side. If the number of IDs is low, and the amount of potential data being returned is high, returning all possible results to the app for filtering is probably the slowest option. The other options are building a dynamic SQL statement that immediately executes the query you want, or building a query to load the into a temp table, and then using the temp table in your primary query. In general, I'd assume that one SQL statement would be faster than two....
    – RDFozz
    Mar 1, 2018 at 17:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.