Sub topic 9
Using read_sql as a single entry point
This chapter assumes you know basic Python, the pandas DataFrame, and the SQL SELECT statement. It also assumes you have read the earlier chapters on connections, read_sql_query and read_sql_table. Here you will see how pandas.read_sql chooses between those two functions, and when to call it directly.
What read_sql does
pandas.read_sql is a thin wrapper. It looks at its first argument and forwards the call to one of two functions:
- If the argument is a SQL query, it calls
read_sql_query. - If the argument is a table name, it calls
read_sql_table.
The keyword arguments you already know (params, index_col, parse_dates, chunksize, columns) are passed on to the function that is chosen.
One function, both uses
The same call works for a query and for a table name. This example builds a small database and reads it both ways.
import sqlite3
import pandas as pd
from sqlalchemy import create_engine
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()
# A query string with a sqlite3 connection
by_query = pd.read_sql(
"SELECT customer, total FROM orders WHERE total >= ?",
conn,
params=(100,),
)
print(by_query)
# A table name with a SQLAlchemy engine
engine = create_engine("sqlite:///shop.db")
by_table = pd.read_sql("orders", engine, index_col="id", columns=["customer", "total"])
print(by_table)The first call receives SQL text, so it behaves like read_sql_query. The second receives a bare name, so it behaves like read_sql_table.
How the dispatch decision is made
The choice depends on the connection and the string, in this order:
- If the connection is a plain DBAPI connection such as
sqlite3, pandas treats the string as a query. Only SQLite is supported this way. - If the connection is a SQLAlchemy engine or connection, pandas checks whether the string names an existing table. If it does, it calls
read_sql_table. - Otherwise, it treats the string as a query and calls
read_sql_query.
Step 2 has a side effect. pandas inspects the database to look for the table name, which costs a small extra round trip. For a query string this check fails, and pandas then falls back to read_sql_query.
| Argument | Connection | Function used |
|---|---|---|
| `"SELECT ..."` | sqlite3 or SQLAlchemy | `read_sql_query` |
| `"orders"` | SQLAlchemy | `read_sql_table` |
| `"orders"` | sqlite3 | Treated as a query, so it fails with a syntax error |
Arguments that only apply to one path
Because read_sql forwards its arguments, some of them make sense only for one of the two functions. The difference matters when the route changes.
| Argument | Used by `read_sql_query` | Used by `read_sql_table` |
|---|---|---|
| `params` | Yes | No |
| `columns` | No | Yes |
| `schema` | No | Yes |
| `index_col`, `parse_dates`, `chunksize` | Yes | Yes |
If you pass columns with a query, it is ignored, so you must name the columns in the SELECT list yourself. If you pass params with a table name, there is nothing to bind, and the call is not meaningful.
When to use read_sql, and when not to
Calling read_sql is a reasonable default for short scripts. It lets you change a source from a table to a query without changing the function name.
In shared code, the specific functions are often a better choice for three reasons:
- The name states what the call does. A reader sees
read_sql_queryand knows a query runs. - The behavior does not depend on a lookup. The routing decision in
read_sqlcan change if a table name happens to match a word in your input. - Errors are easier to trace, because the stack trace names the function you chose.
A practical rule is to use read_sql in exploratory work and notebooks, and to use read_sql_query or read_sql_table in code that other people maintain.
Common mistakes
- Passing a table name with a
sqlite3connection and getting a syntax error. - Passing
columnswith a query and expecting it to filter the result. - Mixing parameter styles.
sqlite3uses?, while SQLAlchemy withtext()uses:name. - Assuming
read_sqlis faster than the specific functions. It adds a table lookup on SQLAlchemy connections and does no other work.
Exercise
You call pd.read_sql("customers", conn, columns=["name"]) where conn is a sqlite3 connection. What happens, and how would you get only the name column?
Show answer
pandas treats "customers" as SQL text because the connection is not SQLAlchemy, so SQLite raises a syntax error and columns is never used. Either call pd.read_sql("SELECT name FROM customers", conn), or create a SQLAlchemy engine and call pd.read_sql("customers", engine, columns=["name"]).
Exercise
Which function does pd.read_sql("SELECT * FROM orders WHERE total >= :min", connection, params={"min": 100}) end up calling, assuming connection is a SQLAlchemy connection and the query is wrapped in text()? Why do you need text() for the named parameter?
Show answer
It calls read_sql_query, because the argument is SQL and not a table name. text() tells SQLAlchemy to bind the :min placeholder from the params dictionary. Without it, the raw string is sent to the driver, which may not accept the named style.