Search code examples
pythonsqlsqlite

INNER JOIN with a Python list


I am trying to select from a table where values of one of the columns are equal to values of a list:

SQLite table:

ID price
a 100
b 200
z 2600

Python list:

["a", "d" , "e"]

I want to find the prices of each of those ID's. The obvious way is JOIN on ID but that list is not a table. How can I do this?


Solution

  • You could write the list to a temporary table, and join with that. To make the join more efficient, ensure that at least one of the join columns (preferrably that of the smaller table) is indexed.

    However, if the list is not too long, you can simply use the IN operator:

    SELECT *
    FROM MyTable
    WHERE ID IN ('a', 'd', 'e')