Sub topic 10
Diagnosing common errors and warnings
This chapter assumes you have worked through the earlier chapters. You should know how to connect with sqlite3 or a SQLAlchemy engine, call read_sql_query with params, and set index_col, parse_dates and dtype. Here you will learn to recognize the failures that come up most often, find which layer caused each one, and fix it.
Find the layer that failed
A call like pd.read_sql_query(sql, con, params=...) passes through four layers:
- Your Python code builds the SQL string and the parameters.
- pandas picks a code path based on the type of
con. - The driver (
sqlite3,psycopg2,pymysql) binds the parameters and sends the statement. - The database parses and runs the statement.
Each layer reports problems in its own way. Reading the traceback from the bottom up usually shows which layer you are dealing with.
- With a raw
sqlite3connection, pandas wraps driver errors inpandas.errors.DatabaseError. The message starts withExecution failed on sql '...', and the original error is attached as__cause__. - With a SQLAlchemy engine or connection, errors usually surface as
sqlalchemy.excclasses such asOperationalErrororProgrammingError. These also carry the original driver error. - Warnings and
ImportErrorcome from pandas itself, before any SQL runs. - Wrong dtypes and surprising shapes raise nothing. You notice them when you inspect the DataFrame.
The script below creates two small tables and triggers several failures on purpose. Each failure is caught and printed with its cause, so you can see the layers.
import sqlite3
import pandas as pd
conn = sqlite3.connect(":memory:")
conn.executescript("""
CREATE TABLE orders (id INTEGER PRIMARY KEY, customer TEXT, total REAL, created_at TEXT);
INSERT INTO orders VALUES
(1, 'Ada', 120.5, '2024-01-05'),
(2, 'Grace', 80.0, '2024-01-09'),
(3, 'Ada', 200.0, '2024-02-01');
CREATE TABLE items (id INTEGER PRIMARY KEY, qty INTEGER);
INSERT INTO items VALUES (1, 5), (2, NULL), (3, 7);
""")
def attempt(label, func):
try:
func()
except Exception as exc:
print(f"{label}: {type(exc).__name__}: {exc}")
print(f" cause: {exc.__cause__!r}")
attempt(
"misspelled table",
lambda: pd.read_sql_query("SELECT * FROM order", conn),
)
attempt(
"string instead of tuple",
lambda: pd.read_sql_query(
"SELECT * FROM orders WHERE customer = ?", conn, params=("Ada")
),
)
attempt(
"wrong placeholder style",
lambda: pd.read_sql_query(
"SELECT * FROM orders WHERE customer = %s", conn, params=("Ada",)
),
)
attempt(
"table name given to read_sql",
lambda: pd.read_sql("orders", conn),
)Run it and compare the four messages. Each one is explained in the sections below.
Warnings about the connection object
The most common pandas warning is this one:
UserWarning: pandas only supports SQLAlchemy connectable (engine/connection) or
database string URI or sqlite3 DBAPI2 connection. Other DBAPI2 objects are not tested.
Please consider using SQLAlchemy.pandas emits it when you pass a raw driver connection that is not a sqlite3 connection. For example, psycopg2.connect(...) or pymysql.connect(...) triggers it. The query often still runs, but pandas has not tested that code path. Behavior can differ in details such as parameter handling, type conversion and transaction state.
The fix is to hand pandas a SQLAlchemy engine or connection. The driver stays the same, and only the object you pass changes. A PostgreSQL URL looks like postgresql+psycopg2://user:password@host:5432/dbname. The example below uses SQLite so it runs anywhere.
import pandas as pd
from sqlalchemy import create_engine
engine = create_engine("sqlite:///shop.db")
with engine.connect() as connection:
df = pd.read_sql_query("SELECT 1 AS one", connection)
print(df)Passing the URL string directly to read_sql_query also works, but pandas then opens a new engine on every call. That is wasteful in a loop. Create one engine and reuse it.
Two related import errors:
ImportError: Using URI string without sqlalchemy installed.You passed a URL string but SQLAlchemy is not installed. Runpip install sqlalchemy.- A missing-driver error such as
ModuleNotFoundError: No module named 'psycopg2'comes from SQLAlchemy, not pandas. Install the driver your URL names.
Parameter errors
Placeholder style depends on the driver
Each driver accepts its own placeholder style, and pandas does not translate between them.
| Connection | Accepted styles | Example |
|---|---|---|
| `sqlite3` connection | `?` (qmark), `:name` (named) | `WHERE customer = ?` |
| `psycopg2` or `pymysql` connection | `%s` (format), `%(name)s` (pyformat) | `WHERE customer = %s` |
| SQLAlchemy connection with `text()` | `:name` | `WHERE customer = :name` |
When you use %s with sqlite3, SQLite sees a literal % and fails with a syntax error near %. When you use ? with psycopg2, the driver reports a syntax error near ?. In both cases the SQL text is wrong for that driver, and no params change will fix it.
Raw strings with a SQLAlchemy connection
With SQLAlchemy, a plain string is sent to the driver as-is, so it needs the driver's style. Only a text() object gets SQLAlchemy's portable :name style. SQLite understands :name natively, so a raw string with :name happens to work on SQLite. The same code on PostgreSQL fails, because psycopg2 expects %(name)s. To stay portable, wrap the query in text().
Using text() with a raw sqlite3 connection does not work. sqlite3 expects a string, so use text() only with SQLAlchemy.
A string is not a one-element tuple
params=("Ada") is the string "Ada", because parentheses without a trailing comma do not make a tuple. sqlite3 treats the string as a sequence of three characters and reports something like Incorrect number of bindings supplied. The current statement uses 1, and there are 3 supplied. The fix is params=("Ada",).
The same message appears when the number of placeholders and the number of values really differ. Count the ? marks and the values.
Placeholders cannot stand in for names
A placeholder binds a value, never a table or column name. This query does not do what it appears to do:
pd.read_sql_query("SELECT ? FROM orders", conn, params=("total",))SQLite returns the literal text total on every row, not the column. If a column name comes from a user, check it against an allow-list of known names and then insert it into the SQL text. Never pass it through params, and never concatenate it unchecked.
Lists in IN clauses
WHERE id IN ? with a list fails, because one placeholder binds one value. Generate one placeholder per item. You only format the placeholders into the SQL, never the values, so this stays safe from injection.
ids = [1, 3]
if ids:
placeholders = ",".join("?" for _ in ids)
sql = f"SELECT id, customer FROM orders WHERE id IN ({placeholders})"
df = pd.read_sql_query(sql, conn, params=ids)
print(df)The if ids: guard matters. An empty list produces IN (), which some databases reject. Decide what an empty list should mean, usually an empty result, and handle it before the query.
A literal percent sign with %s-style drivers
With psycopg2 or pymysql, a literal % in SQL must be doubled when parameters are passed. A pattern such as LIKE 'A%' becomes LIKE 'A%%'. A better approach is to pass the whole pattern as a parameter, for example params=("A%",), so the SQL text has no % at all.
Errors that say the table or column does not exist
The empty database from a wrong path
sqlite3.connect("shop.db") creates an empty file if none exists. If your script runs from a different working directory than you expected, you get a fresh empty database. The next query then fails with no such table: orders, even though the table exists in another file. When you see that message, check these in order:
- Print
os.path.abspath("shop.db")and confirm it is the file you meant. - Check that the file size is not zero.
- List the tables with
SELECT name FROM sqlite_master WHERE type = 'table'.
You can also open the file read-only with sqlite3.connect("file:shop.db?mode=ro", uri=True). A missing file then raises an error instead of being created.
read_sql_table
read_sql_table raises ValueError: Table orders not found when the name does not match. Causes include:
- Case differences. PostgreSQL folds unquoted names to lower case, but a table created with quotes keeps its case.
- A table in a non-default schema, which needs
schema="sales". - A name that refers to a view. Check that your pandas and SQLAlchemy versions support reflecting views.
read_sql_table also requires SQLAlchemy. It does not work with a raw sqlite3 connection.
Passing a table name to read_sql with a sqlite3 connection
read_sql chooses between the query and table readers by the type of con. A sqlite3 connection supports only queries, so pd.read_sql("orders", conn) sends the text orders to SQLite as a statement. The result is DatabaseError: Execution failed on sql 'orders': near "orders": syntax error. Either write SELECT * FROM orders or switch to a SQLAlchemy engine.
Surprises in the DataFrame
Integers with NULL become floats
A numeric column that contains NULL is read as float64 with NaN, because plain NumPy integer columns cannot hold missing values. Request a nullable dtype to keep integers:
df = pd.read_sql_query("SELECT id, qty FROM items", conn)
print(df.dtypes)
df = pd.read_sql_query(
"SELECT id, qty FROM items", conn, dtype={"qty": "Int64"}
)
print(df.dtypes)
print(df)The first call gives qty as float64. The second gives Int64, and the missing value prints as <NA>. If you want nullable types for every column, pass dtype_backend="numpy_nullable" in pandas 2.0 or later.
Dates stay as text
SQLite has no native date type, and many other columns are stored as text or integers. Without parse_dates, such columns arrive as object strings. Two problems follow:
- You cannot use the
.dtaccessor on them. - Sorting works only if the text format sorts correctly, as ISO
YYYY-MM-DDdoes.
Add parse_dates=["created_at"] as shown in the chapter on types. If parsing raises a ValueError about data not matching the format, the column contains mixed formats or placeholder strings such as "N/A". Parse it yourself afterwards and make bad values visible:
df = pd.read_sql_query("SELECT id, created_at FROM orders", conn)
df["created_at"] = pd.to_datetime(df["created_at"], errors="coerce")
print(df["created_at"].isna().sum(), "unparseable dates")With errors="coerce", bad values become NaT, so count them rather than ignoring them.
Duplicate column names after a JOIN
SELECT o.id, c.id FROM ... produces two columns both named id. Column selection by name then returns a DataFrame instead of a Series, and index_col="id" is ambiguous. Alias each column in SQL, for example o.id AS order_id, c.id AS customer_id.
index_col not found
index_col="ID" on a column named id raises a KeyError. The name must match the column label in the result, which is the alias if you used AS. Print df.columns on a query without index_col first.
Empty results
If no rows match, you still get a DataFrame with the right column names but zero rows. Because there are no values to infer from, the dtypes are usually object. Code that then does arithmetic or date operations may fail oddly. Test df.empty right after the read.
Problems with chunksize
With chunksize, read_sql_query returns an iterator of DataFrames, not a DataFrame. Two errors follow from that:
AttributeErrorsuch as'generator' object has no attribute 'shape'. You used the return value as a DataFrame. Loop over it, or callpd.concat(...)on it.sqlite3.ProgrammingError: Cannot operate on a closed database.(or the equivalent SQLAlchemy error) means you closed the connection before consuming the iterator. Chunks are fetched lazily, so the connection must stay open for the whole loop. Put the loop inside thewithblock.
A subtler problem is that memory use may not fall. With some drivers, such as psycopg2, the default cursor downloads the whole result to the client first, and chunksize only slices what is already in memory. To make the database stream rows, ask SQLAlchemy for a server-side cursor:
from sqlalchemy import create_engine
import pandas as pd
engine = create_engine("sqlite:///shop.db")
with engine.connect().execution_options(stream_results=True) as connection:
total = 0.0
for chunk in pd.read_sql_query("SELECT * FROM orders", connection, chunksize=2):
total += chunk["total"].sum()
print(total)SQLite reads rows incrementally anyway, so the option changes nothing there. On PostgreSQL it makes the difference between holding the whole result and holding one chunk.
Version mismatches
Many "it worked yesterday" failures come from package upgrades.
- pandas older than 2.0 with SQLAlchemy 2.x. The usual symptom is
AttributeError: 'OptionEngine' object has no attribute 'execute', because SQLAlchemy 2.0 removedEngine.execute. Upgrade pandas to 2.0 or later. Pinningsqlalchemy<2also works, but it only postpones the upgrade. - Your own code calling
engine.execute(...). That method is also gone in SQLAlchemy 2.x. Usewith engine.connect() as connection:andconnection.execute(text(...)). - Missing commits. In SQLAlchemy 2.x, a connection starts a transaction automatically and does not commit it. This matters when you write setup data and then read it through another connection. Call
connection.commit(), or usewith engine.begin() as connection:.
Check what you have with python -c "import pandas, sqlalchemy; print(pandas.__version__, sqlalchemy.__version__)" before searching for other causes.
A triage routine
When a read fails, work through the questions in this order. The diagram follows the same sequence.
If you cannot find the cause, run the same SQL with the same values in a database client such as the sqlite3 shell or psql. If it fails there, the problem is in the SQL, not in pandas. If it works there, compare the connection, the driver and the parameter style.
Quick reference
| Symptom | Likely cause | Fix |
|---|---|---|
| `UserWarning: pandas only supports SQLAlchemy connectable...` | Raw non-sqlite3 DBAPI connection | Pass a SQLAlchemy engine |
| `Incorrect number of bindings supplied` | `params=("Ada")` or wrong count | Use `("Ada",)`, count the placeholders |
| Syntax error near `%` or `?` | Placeholder style does not match the driver | Use the driver's style, or `text()` with SQLAlchemy |
| `no such table` on a table you created | Empty file from a wrong path | Check the absolute path and `sqlite_master` |
| `Table ... not found` from `read_sql_table` | Case, schema or SQLAlchemy missing | Set `schema`, check the name |
| `Execution failed on sql 'orders'` | Table name passed to `read_sql` with sqlite3 | Write a `SELECT` or use an engine |
| Integer column is `float64` | NULL values | `dtype={"col": "Int64"}` |
| Date column is `object` | No `parse_dates` | `parse_dates=[...]` or `pd.to_datetime` |
| `'generator' object has no attribute ...` | `chunksize` returns an iterator | Loop over it or `pd.concat` |
| `Cannot operate on a closed database` | Connection closed before iterating | Iterate inside the `with` block |
| `'OptionEngine' object has no attribute 'execute'` | pandas older than 2.0 with SQLAlchemy 2.x | Upgrade pandas |
Exercise
A colleague writes pd.read_sql_query("SELECT * FROM orders WHERE customer = ?", conn, params=("Ada")) against a sqlite3 connection and gets "Incorrect number of bindings supplied. The current statement uses 1, and there are 3 supplied." What is wrong, and how do you fix it?
Show answer
("Ada") is just the string "Ada", not a tuple. sqlite3 treats the string as a sequence of its three characters, so it sees three values for one placeholder. Write params=("Ada",) with a trailing comma, or params=["Ada"].
Exercise
You run the same query through a psycopg2 connection and pandas prints a UserWarning that starts "pandas only supports SQLAlchemy connectable". The query returns correct data. Should you ignore the warning? What do you change?
Show answer
Do not ignore it. pandas has not tested raw DBAPI connections other than sqlite3, so details of parameter handling and type conversion may differ. Create a SQLAlchemy engine with create_engine("postgresql+psycopg2://user:password@host:5432/dbname"), pass it (or a connection from engine.connect()) to pandas, and use text() with :name parameters or the driver's placeholder style.
Exercise
A table has an integer column qty where some rows are NULL. After read_sql_query, qty has dtype float64. Which argument keeps the values as integers, and how do missing values appear?
Show answer
Pass dtype={"qty": "Int64"}, or dtype_backend="numpy_nullable" in pandas 2.0 or later. The column then has the nullable integer dtype Int64, and missing values appear as <NA> instead of NaN.