SQL Databases
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
Most business data lives in relational databases, and pandas can pull the result of a query straight into a DataFrame
and push a DataFrame back as a table. This page covers the three readers (read_sql, read_sql_query and
read_sql_table), the writer DataFrame.to_sql, the three kinds of connection pandas accepts, parameter binding
(the defence against SQL injection), chunked reading, type mapping and the transaction behaviour that surprises people.
The page targets Python 3.13 or 3.14 and pandas 3.1 and was checked in October 2026. The examples were run on pandas
3.1.0 with SQLAlchemy 2.1.6 and SQLite through the standard-library sqlite3 module. The ADBC example ran on pandas
3.1.0 with adbc-driver-sqlite 1.13. Drivers for PostgreSQL, MySQL or SQL Server were not run here; the examples that name
them only change the connection string. For the language of the queries themselves see
SQL queries and Transactions, and for how SQL
concepts map onto pandas operations see Coming from SQL.
Three kinds of connection
pandas does not talk to databases directly. The con argument accepts one of:
-
a SQLAlchemy
EngineorConnection(or a URL string, which pandas turns into an engine). SQLAlchemy needs a separate driver for each database, for examplepsycopgfor PostgreSQL orpymysqlfor MySQL. -
an ADBC connection (Arrow Database Connectivity). The pandas documentation prefers ADBC drivers when one exists for the database, and native ADBC support was added in pandas 2.2.0. Results travel as Arrow data, so types are exact and no row-by-row conversion is needed.
-
a plain DBAPI
sqlite3.Connectionfrom the standard library, with no extra packages.
python -m pip install "pandas>=3.1" sqlalchemy # engine-based access
python -m pip install psycopg[binary] # a driver for PostgreSQL
python -m pip install adbc-driver-sqlite # ADBC driver for SQLite
python -m pip install adbc-driver-postgresql # ADBC driver for PostgreSQL
Source: pandas user guide: SQL queries
Differences that matter:
-
read_sql_tablemust have an ADBC driver or SQLAlchemy; it does not work with a baresqlite3connection. -
The
paramsargument ofread_sqlis not implemented for ADBC connections in pandas 3.1.0; the call raisesNotImplementedError. Use SQLAlchemy orsqlite3when you need bound parameters through pandas. -
You are responsible for closing a connection you opened yourself.
A sample database
The examples use a small SQLite file so that they run anywhere. For a server database change only the URL; keep the password out of the source code and read the URL from an environment variable.
import pandas as pd
from sqlalchemy import create_engine, text
engine = create_engine("sqlite:///shop.db")
# For PostgreSQL: create_engine(os.environ["DATABASE_URL"])
# with DATABASE_URL = "postgresql+psycopg://user@host:5432/shop" (password from a secret store)
df = pd.DataFrame({
"order_id": [1, 2, 3, 4, 5],
"country": ["ES", "FR", "ES", "DE", None],
"amount": [10.5, 20.0, None, 7.25, 3.0],
"ordered": pd.to_datetime([
"2026-01-01", "2026-01-02", "2026-02-01", "2026-02-15", "2026-03-01",
]),
"ok": [True, False, True, True, False],
})
written = df.to_sql("orders", engine, index=False)
print("rows written:", written)
rows written: 5
to_sql returns the number of rows affected, or None if the driver does not report it.
Source: pandas.DataFrame.to_sql
Reading
read_sql, read_sql_query and read_sql_table
-
read_sql_query(sql, con)runs a query and returns its result. -
read_sql_table(table_name, con)reads a whole table (optionally somecolumns) and needs SQLAlchemy or ADBC. -
read_sql(sql, con)is a convenience wrapper that behaves asread_sql_queryfor a SQL string and asread_sql_tablefor a table name. In practice most code passes a query, so preferread_sql_queryorread_sqlwith a query and be explicit.
q = "SELECT country, SUM(amount) AS total FROM orders GROUP BY country ORDER BY country"
print(pd.read_sql_query(q, engine))
print(pd.read_sql_table("orders", engine, index_col="order_id", columns=["amount"]).head(2))
country total
0 NaN 3.00
1 DE 7.25
2 ES 10.50
3 FR 20.00
amount
order_id
1 10.5
2 20.0
Source: pandas.read_sql_query
NULL becomes NaN in a str column, which is the missing-value marker of the pandas 3 string dtype (see
Text Data and the str Dtype). index_col turns one or more
columns into the index.
Dates and other types
SQLite has no real date type, so the datetimes were stored as text and come back as strings unless you ask for dates.
parse_dates converts columns; dtype forces others.
raw = pd.read_sql("SELECT * FROM orders", engine)
print(raw.dtypes)
typed = pd.read_sql("SELECT * FROM orders", engine, parse_dates=["ordered"], dtype={"order_id": "int32"})
print(typed.dtypes)
order_id int64
country str
amount float64
ordered str
ok int64
dtype: object
order_id int32
country str
amount float64
ordered datetime64[us]
ok int64
dtype: object
Source: pandas.read_sql
The boolean column came back as int64 because SQLite stores booleans as integers. On PostgreSQL, whose columns have
real types, the same table would return bool and timestamps directly. dtype_backend="pyarrow" or
"numpy_nullable" returns nullable dtypes instead (see PyArrow-Backed Data
and Nullable Integer and Boolean). coerce_float=True (the default) converts
decimal objects to floats.
An empty result has no values to infer types from, so every column is object:
print(pd.read_sql("SELECT * FROM orders WHERE 1 = 0", engine).dtypes.astype(str).tolist())
['object', 'object', 'object', 'object', 'object']
Source: pandas.read_sql
Parameters and SQL injection
Never build a query by pasting a value into the string. A value that comes from a user, a file or another system can carry SQL of its own. Bind parameters instead; the database driver then sends the value separately from the statement and it can never be read as SQL.
bad = "ES' OR '1'='1"
# Wrong: the value becomes part of the statement
leaky = pd.read_sql(f"SELECT * FROM orders WHERE country = '{bad}'", engine)
print(len(leaky), "rows with string formatting")
# Right: a bound parameter
safe = pd.read_sql(text("SELECT * FROM orders WHERE country = :c"), engine, params={"c": bad})
print(len(safe), "rows with a bound parameter")
# Normal use
q = text("SELECT order_id, amount FROM orders WHERE country = :c AND amount > :m")
print(pd.read_sql(q, engine, params={"c": "ES", "m": 5}))
5 rows with string formatting
0 rows with a bound parameter
order_id amount
0 1 10.5
The first query returned all five rows: the injected OR '1'='1' matched everything. The placeholder style depends on
the connection: with SQLAlchemy use text() and named :name parameters (or a SQLAlchemy expression), and with
sqlite3 pass a list for ? placeholders or a dictionary for :name. A placeholder can stand for a value only, never
for a table name or a column name; validate those against a fixed list instead.
SQLAlchemy 2 requires a string to be wrapped in text() when you execute it yourself, and it removed Engine.execute.
Older snippets that call engine.execute("SELECT ...") fail with SQLAlchemy 2; pass the engine to pandas or use a connection
in a with block.
A related trap in SQLAlchemy expressions: where(table.c.flag is True) is evaluated by Python before SQLAlchemy ever sees it
and returns an empty DataFrame. Write table.c.flag.is_(True) or table.c.flag == True.
Reading in chunks
chunksize=n makes read_sql return an iterator of DataFrames of up to n rows.
for chunk in pd.read_sql("SELECT * FROM orders", engine, chunksize=2):
print(len(chunk), end=" ")
print()
2 2 1
Source: pandas.read_sql
By itself this does not save memory. The pandas documentation points out that chunksize only controls how many rows are
converted to a DataFrame at a time, and that the driver may still fetch the whole result first. To really stream, ask the
driver for a server-side cursor:
with engine.connect().execution_options(stream_results=True) as conn:
for chunk in pd.read_sql(text("SELECT * FROM orders"), conn, chunksize=2):
print(len(chunk), end=" ")
print()
2 2 1
Source: pandas.read_sql
Whether stream_results has an effect depends on the database driver. For very large
extracts consider letting the database aggregate first, or exporting to Parquet (see
Parquet, Feather, ORC and Iceberg) and reading that, and see
Scaling to Large Datasets. For slow queries on the database side see
Diagnosing Slow Queries.
An ADBC connection
from adbc_driver_sqlite import dbapi
with dbapi.connect("adbc.db") as conn:
df.drop(columns="ordered").to_sql("t", conn, index=False, if_exists="replace")
out = pd.read_sql("SELECT * FROM t WHERE order_id > 2", conn)
print(out.dtypes.astype(str).to_dict())
conn.commit()
{'order_id': 'int64', 'country': 'str', 'amount': 'float64', 'ok': 'int64'}
Source: pandas.read_sql
ADBC connections follow the DBAPI convention of an implicit transaction, so call conn.commit() yourself when you
use one for writes.
Writing with to_sql
try:
df.to_sql("orders", engine, index=False) # the table exists and if_exists is "fail"
except ValueError as exc:
print("ValueError:", exc)
print(df.to_sql("orders", engine, index=False, if_exists="append"))
print(pd.read_sql("SELECT COUNT(*) AS n FROM orders", engine))
print(df.to_sql("orders", engine, index=False, if_exists="replace"))
ValueError: Table 'orders' already exists.
5
n
0 10
5
Source: pandas.DataFrame.to_sql
if_exists decides what happens when the table exists:
| Value | Behaviour |
|---|---|
|
Raise |
|
Insert the rows into the existing table. The columns must match. |
|
Drop the table, recreate it from the DataFrame and insert the rows. Indexes, constraints and column types you defined in the database are lost. |
|
Keep the table and its definition but delete its rows first, then insert. Present in the pandas 3.1 signature; prefer
it to |
Other arguments of to_sql:
-
index=Falseomits the DataFrame index; with the defaultindex=Trueit is written as a column (named byindex_labelor the index name). -
schemaselects a database schema where the database has them. -
dtypeoverrides the column types, with SQLAlchemy types for engines:from sqlalchemy import Integer, String df.to_sql("orders2", engine, index=False, if_exists="replace", dtype={"country": String(2), "order_id": Integer()}) with engine.connect() as conn: print(conn.execute(text("SELECT sql FROM sqlite_master WHERE name = 'orders2'")).scalar())CREATE TABLE orders2 ( order_id INTEGER, country VARCHAR(2), amount FLOAT, ordered DATETIME, ok BOOLEAN )Source: pandas.DataFrame.to_sql
-
method="multi"puts several rows in a singleINSERT; a callable lets you plug in a database-specific bulk loader such as PostgreSQLCOPY.chunksizelimits rows per batch and avoids packet-size errors on large writes.
A table written by pandas has no primary key and no foreign keys. For real tables create them with SQL or SQLAlchemy
models first and then use if_exists="append" or "delete_rows".
Type mapping surprises
-
timedeltacolumns are not supported: pandas writes plain integers and emits aUserWarningthat says "ns frequency". With the pandas 3 default microsecond resolution one hour was stored as 3600000000, so check the unit before relying on the numbers. The exception is the ADBC PostgreSQL driver, which writes anINTERVAL. -
Categorical columns are written as plain values and do not come back as categories; convert after reading (see Categorical Data).
-
Databases without time-zone support (SQLite, MySQL) store naive local timestamps. A time-zone-aware column written to SQLite came back as a naive
2026-01-01 12:00:00string. PostgreSQLTIMESTAMP WITH TIME ZONEis read back converted to UTC. -
Object columns holding Python lists or dictionaries cannot be written to most databases; serialise them first.
-
With SQL Server and
pyodbc,fast_executemany=Truecan lose precision on local temporary tables (#name); the pandas guide suggestsUseFMTONLY=Yesin the connection string or global temporary tables (##name).
Transactions
to_sql and the readers use the connection you give them. With an Engine, pandas opens its own connection and commits
after the write. With a Connection or ADBC connection you control the transaction:
with engine.begin() as conn: # commits on success, rolls back if an exception escapes
df.to_sql("orders4", conn, index=False, if_exists="replace")
print(pd.read_sql("SELECT COUNT(*) AS n FROM orders4", conn).iloc[0, 0])
5
Source: pandas.DataFrame.to_sql
Using one connection for a read-modify-write sequence keeps it atomic. For the theory of transactions and isolation levels see
Transactions. pandas is a poor tool for concurrent updates of individual rows: to
change a few rows run an UPDATE through SQLAlchemy instead of rewriting the table.
The standard-library sqlite3 route
import sqlite3
con = sqlite3.connect("shop.db")
print(pd.read_sql("SELECT order_id FROM orders LIMIT 2", con))
try:
pd.read_sql_table("orders", con)
except NotImplementedError as exc:
print(exc)
con.close()
order_id
0 1
1 2
read_sql_table not supported for a DBAPI connection. Use read_sql_query, or pass a SQLAlchemy connectable.
sqlite3 is enough for local files and tests. Close the connection yourself, or wrap it with contextlib.closing,
because the connection’s with block only manages the transaction, not the closing.
Pitfalls summary
-
Bind parameters; never format values into SQL strings.
-
chunksizeis not streaming without a server-side cursor. -
if_exists="replace"drops constraints and indexes; prefer"append"or"delete_rows"on tables you designed. -
Dates and booleans may come back as strings or integers on databases that lack those types; use
parse_datesanddtype. -
An empty result is all
object. -
Do not put database passwords in notebooks or in version control (see Ethics, Privacy and Responsible Data Use).
Where older tutorials are outdated
| Older statement | Current situation (October 2026) |
|---|---|
|
|
|
The |
"pandas only supports SQLAlchemy and sqlite3" (before 2024) |
ADBC connections are supported since pandas 2.2.0 and preferred by the documentation where a driver exists. |