Use one placeholder per string
To match several text values, write one placeholder for each item in an IN clause, and pass the list as the parameters:
names = ["Ava", "Ben", "Chen"]
placeholders = ",".join(["?"] * len(names))
sql = f"SELECT id, customer, total FROM orders WHERE customer IN ({placeholders})"
cur.execute(sql, names)
rows = cur.fetchall()
The placeholders string becomes ?,?,?. The f-string inserts only question marks, and each name is passed as its own parameter.
This works with sqlite3 and with pyodbc, which both use ?. With psycopg2 or PyMySQL, use %s in place of ?.
Handle an empty list first
If the list might be empty, skip the query. IN () is a syntax error in several databases, so the code should not build it:
if not names:
return []
The return assumes this code sits inside a function.
Trim spaces and check case
Stray spaces from user input can stop a match, so trim the values with .strip() in Python before the query:
names = [name.strip() for name in names]
Whether "ava" matches "Ava" depends on the database’s collation and settings, so test the case behavior with your own data. For cleaning values in SQL instead, see what does trim() do in SQL.
PostgreSQL: pass the list as one array
With psycopg2, pass the Python list to ANY:
cur.execute(
"SELECT id, customer, total FROM orders WHERE customer = ANY(%s)",
(names,),
)
psycopg2 converts the list to a PostgreSQL array, so the query has one placeholder however long the list is.
SQL Server: split one delimited string
pyodbc cannot bind a Python list to one placeholder. One option is to join the names into a single comma-separated string and split it inside the query with STRING_SPLIT. The function needs SQL Server 2016 or later, with the database at compatibility level 130 or higher:
csv_names = ",".join(names)
sql = """
SELECT id, customer, total
FROM orders
WHERE customer IN (SELECT value FROM STRING_SPLIT(?, ','))
"""
cur.execute(sql, (csv_names,))
This breaks if a name contains a comma, so use it only for values you know cannot include commas.
Long lists and SQLAlchemy
SQL Server documents a limit of 2,100 parameters for a stored procedure, so a very long list can run into a limit. For long lists, a common approach is to load the values into a temporary table and join to it.
With SQLAlchemy, a column’s in_() method takes the list and builds the placeholders for you. With a mapped Order class, the query looks like this:
stmt = select(Order).where(Order.customer.in_(names))