SQL From Python

How do I put variables into a string?

Use an f-string to put a variable into text in Python. Learn why string building is unsafe for SQL and how placeholders keep values out of the query.

On this page
  1. Use an f-string to put a variable into text
  2. These methods are for text, not SQL
  3. Pass the value as a parameter instead
  4. Build table and column names from a fixed list
  5. Joining text inside SQL

Use an f-string to put a variable into text

In Python 3.6 and later, an f-string puts a variable into a string. Put an f before the opening quote, and write the variable name in braces:

name = "Ava"
total = 120.5
print(f"{name} spent {total:.2f}")  # Ava spent 120.50

The :.2f after total formats the number with two decimal places.

Two older methods do the same job, str.format() and % formatting. You will see them in older code:

print("{} spent {:.2f}".format(name, total))
print("%s spent %.2f" % (name, total))

Both lines print the same text as the f-string.

These methods are for text, not SQL

All three methods build a new string. That works well for messages, file names and log lines. It is a poor fit for SQL, because the value becomes part of the query:

name = "' OR '1'='1"
sql = f"SELECT id, total FROM orders WHERE customer = '{name}'"  # avoid

With this value, the WHERE clause matches every row. That is SQL injection. Even without an attacker, a value with an apostrophe, such as O'Brien, breaks the query.

Pass the value as a parameter instead

Use a placeholder in the SQL, and pass the value separately:

sql = "SELECT id, total FROM orders WHERE customer = ?"
cur.execute(sql, (name,))

Here the value is data, not SQL, and the driver handles the quoting. The comma in (name,) matters: it makes a one-item tuple, while (name) is just the string. The ? is the sqlite3 placeholder. Other drivers use other placeholders; see how to pass variable in sql query in python for a table of them.

Build table and column names from a fixed list

Table and column names cannot be placeholders in most drivers. When one depends on input, look it up in a dictionary you control:

SORT_COLUMNS = {"date": "order_date", "total": "total"}

column = SORT_COLUMNS.get(sort_choice)
if column is None:
    raise ValueError("unknown sort choice")
sql = f"SELECT id, total FROM orders ORDER BY {column}"

Only names from the dictionary reach the query text.

Joining text inside SQL

Sometimes text should be joined inside the query, such as combining a first name column and a last name column. That is an SQL job, and the operator depends on the database:

  • PostgreSQL and SQLite use ||.
  • SQL Server uses +.
  • MySQL uses CONCAT(), because || means OR there unless the PIPES_AS_CONCAT mode is on.

For how the || operator works, see what is the use of || in SQL.

The complete guide to sql from python

How to Pass a Variable in an SQL Query in Python
Read the guide

Keep exploring

Guides from other topics

All topics →