Sub topic 9
Using read_sql as a single entry point
This chapter assumes you can already load a query with read_sql_query and a table with read_sql_table, and that you know the difference between a sqlite3 connection and a SQLAlchemy engine. It covers pandas.read_sql, the one function that wraps both readers, and the rules that decide which reader it calls.
What read_sql does
pandas.read_sql takes a sql argument and a connection con. It then calls one of the two functions you already know:
read_sql_query, whensqlshould be executed as a SQL statement.read_sql_table, whensqlis the name of a table.
It does not add any new loading capability. Everything it returns could be loaded by calling the specific function directly. Its value is convenience: one function name covers both cases. Its cost is that the choice happens behind the scenes, and a mistaken choice can produce confusing errors.
The core signature is below. Check your installed version's documentation for the full list, because some arguments were added in pandas 2.x.
pandas.read_sql(
sql,
con,
index_col=None,
coerce_float=True,
params=None,
parse_dates=None,
columns=None,
chunksize=None,
dtype_backend=...,
dtype=None,
)Most of these are the same arguments you used with the specific readers. The sections below cover which of them apply on which path.
The dispatch rule
The decision depends on two inputs: the type of the connection and the value of sql.
In table form:
| Connection | `sql` value | Reader used |
|---|---|---|
| `sqlite3` connection | any string | `read_sql_query` |
| SQLAlchemy engine, connection, or URI string | name of an existing table | `read_sql_table` |
| SQLAlchemy engine, connection, or URI string | a query string such as `SELECT ...` | `read_sql_query` |
| SQLAlchemy engine, connection, or URI string | a SQLAlchemy `text()` or `select()` object | `read_sql_query` |
The important consequence is that a sqlite3 connection never reaches read_sql_table. Table loading needs SQLAlchemy, because it inspects the schema to find column types. The sqlite3 module does not provide that.
Setting up a database to experiment with
The examples in this chapter use the same orders table as the earlier chapters. This block recreates it, so every example here runs on its own.
import sqlite3
import pandas as pd
conn = sqlite3.connect("shop.db")
conn.executescript("""
DROP TABLE IF EXISTS orders;
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');
""")
conn.commit()Using read_sql with a sqlite3 connection
With a sqlite3 connection, read_sql behaves exactly like read_sql_query. All the arguments you know apply:
df = pd.read_sql(
"SELECT id, customer, total, created_at FROM orders WHERE total >= ? AND customer = ?",
conn,
params=(100, "Ada"),
index_col="id",
parse_dates=["created_at"],
)
print(df)
print(df.dtypes)params uses the qmark style (?) because that is what sqlite3 expects. Parameter styles belong to the driver, not to read_sql. The function passes your params through unchanged.
A table name fails on sqlite3
The following call looks reasonable. With a sqlite3 connection it fails:
try:
pd.read_sql("orders", conn)
except pd.errors.DatabaseError as exc:
print("Failed:", exc)Because read_sql cannot load tables through sqlite3, it sends the string orders to the database as SQL. SQLite does not accept that as a statement, so the error is a syntax error. The message looks like Execution failed on sql 'orders': near "orders": syntax error. The message names a SQL problem, but the real cause is the connection type.
With a sqlite3 connection, write the full statement instead:
df = pd.read_sql("SELECT * FROM orders", conn, index_col="id")
print(df)Using read_sql with a SQLAlchemy engine
With an engine, both paths are available. The same function loads a table when you pass a table name and runs a query when you pass SQL:
from sqlalchemy import create_engine, text
engine = create_engine("sqlite:///shop.db")
# Path 1: "orders" is an existing table, so read_sql_table is used.
table_df = pd.read_sql("orders", engine, index_col="id", columns=["customer", "total"])
print(table_df)
# Path 2: not a table name, so read_sql_query is used.
query_df = pd.read_sql(
text("SELECT customer, SUM(total) AS revenue FROM orders GROUP BY customer"),
engine,
)
print(query_df)For the first call, pandas asks the database whether a table called orders exists. It does, so pandas loads the table and applies columns and index_col. For the second call, the text() object is not a table name, so pandas runs it as a query.
Passing a plain string with SELECT also takes the query path, since no table has that name:
with engine.connect() as connection:
ada = pd.read_sql(
text("SELECT * FROM orders WHERE customer = :name"),
connection,
params={"name": "Ada"},
)
print(ada)This also shows the named parameter style that SQLAlchemy's text() uses (:name). It is different from the qmark style used with sqlite3.
Passing a URI string
con can also be a database URI string. pandas creates an engine from it, runs the read, and closes the connection when it finishes:
df = pd.read_sql("orders", "sqlite:///shop.db", index_col="id")
print(df)This is convenient for a one-off read. It is wasteful in a loop, because every call creates a new engine and connection. When you read several times, create one engine and reuse it.
Which arguments apply on which path
The arguments are shared in the signature, but not all of them affect both paths. A table-path call and a query-path call to the same function read different arguments, and an ignored argument does not raise an error.
| Argument | Query path | Table path |
|---|---|---|
| `params` | Used | Not used |
| `columns` | Not used | Used |
| `index_col` | Used | Used |
| `parse_dates` | Used | Used |
| `chunksize` | Used | Used |
| `coerce_float` | Used | Used |
| `dtype` | Used | Not used |
You can see this by passing columns along with a query:
df = pd.read_sql("SELECT * FROM orders", engine, columns=["customer"])
print(list(df.columns))The output still lists all four columns. columns is only used to choose columns from a table, and a query path never looks at it. If you want fewer columns from a query, name them in the SELECT list. A call that passes params along with a table name behaves the same way in reverse: the values are silently dropped.
read_sql also has no schema argument. If a table lives outside the connection's default schema, call read_sql_table directly with its schema argument, or write a query that names the schema.
Gotchas
The dispatch is by name, so ambiguity is possible
On the engine path, a string is treated as a table name whenever a table with exactly that name exists. If you meant a query, the check changes nothing, because a real query does not match a table name. The reverse mistake is the common one. A misspelled table name, such as "ordres", does not exist, so pandas treats it as SQL and the database returns a syntax error. You get a SQL error for what is really a typo in a table name.
The existence check costs a round trip
Before reading, pandas asks the database about its tables. That check is cheap on a local SQLite file. Across a network, it adds a small delay to every call. If you call read_sql thousands of times, use read_sql_query or read_sql_table directly to skip the check.
Other DBAPI connections give a warning
pandas supports SQLAlchemy engines and connections, URI strings, and sqlite3 connections. If you pass another DBAPI connection, such as one from psycopg2 or pymysql, pandas typically emits a UserWarning saying only SQLAlchemy connectables, URI strings and sqlite3 connections are tested. The read often still works, but the warning means the behavior is not guaranteed. It never means your SQL is wrong. The earlier chapter on common errors covers the fix: pass a SQLAlchemy engine instead.
Behavior depends on your pandas version
Details such as the dtype argument and the supported connection types changed between pandas 1.x and 2.x. When something looks different from this chapter, check pd.__version__ and the documentation for that version.
Choosing between read_sql and the specific functions
Both styles produce the same DataFrame for the same inputs. Use these criteria to decide.
| Situation | Better choice |
|---|---|
| Quick exploration, one connection type, you know what you are passing | `read_sql` |
| Library or pipeline code that must be predictable | `read_sql_query` or `read_sql_table` |
| You use `sqlite3` | `read_sql` or `read_sql_query`, which are equivalent |
| You need `schema` or you want a table-only guarantee | `read_sql_table` |
| High-frequency reads over a network | A specific function, to skip the table check |
In shared code, naming the specific function makes the intent visible to the next reader. A call to read_sql_query states that you are running SQL, and an accidental table-name match cannot change that. A call to read_sql makes the reader work out which path runs.
One approach is to use read_sql interactively and a specific function in code that others will maintain. Another is to wrap the choice in your own function, so the rule is stated once:
def load_table(name, engine, **kwargs):
"""Load a whole table. Fails clearly if the table does not exist."""
return pd.read_sql_table(name, engine, **kwargs)
def run_query(sql, con, **kwargs):
"""Run a SQL statement."""
return pd.read_sql_query(sql, con, **kwargs)
print(load_table("orders", engine, index_col="id"))
print(run_query("SELECT COUNT(*) AS n FROM orders", conn))The helper load_table raises a ValueError when the table is missing. That is a clearer failure than a confusing SQL syntax error.
Close the connections when you are finished:
conn.close()
engine.dispose()Exercise
You run pd.read_sql("orders", conn, columns=["customer"]) where conn is a sqlite3 connection. What happens, and why? How would you get only the customer column?
Show answer
It fails with a pandas DatabaseError that wraps a SQLite syntax error. With a sqlite3 connection, readsql always uses readsqlquery, so the string "orders" is sent as SQL, and columns is not used on that path anyway. To get only the customer column, run pd.readsql("SELECT customer FROM orders", conn), or create a SQLAlchemy engine and call pd.read_sql("orders", engine, columns=["customer"]).
Exercise
With a SQLAlchemy engine, pd.read_sql("SELECT * FROM orders WHERE customer = :name", engine, params={"name": "Ada"}) is a plain string with a named parameter. Why might it fail even though the params dictionary is valid, and what is the fix?
Show answer
A plain string passed to the driver does not use SQLAlchemy's named parameter style, so the :name placeholder can cause a parameter style error with some drivers. Wrap the statement in sqlalchemy.text(), as in pd.read_sql(text("SELECT * FROM orders WHERE customer = :name"), engine, params={"name": "Ada"}). The text() construct tells SQLAlchemy to bind :name itself.
Exercise
Name two arguments that read_sql accepts but only uses on one path, and say which path uses each.
Show answer
params is used only on the query path, and columns is used only on the table path. dtype is also used only on the query path. An argument that does not apply to the chosen path is ignored without an error.