Sub topic 8
Loading whole tables with read_sql_table
pandas.read_sql_table loads one database table into a DataFrame without you writing any SQL. This chapter covers how it works internally, which options it supports, how it differs from read_sql_query, and the errors you are likely to meet.
This chapter assumes you have these prerequisites:
- Basic Python, including functions and context managers.
- Basic pandas: DataFrame, columns, dtypes.
- The earlier chapters of this tutorial: connecting with sqlite3 and SQLAlchemy, and running queries with
read_sql_query. - SQLAlchemy installed (
pip install sqlalchemy). The examples use SQLite, which ships with Python, so no database driver is needed.
What read_sql_table does
read_sql_table(table_name, con, ...) takes a table name and a SQLAlchemy connectable. A connectable is an engine or a connection. It does not take a query string.
Internally it works in four steps:
- It asks the database which columns the table has and what their types are. SQLAlchemy calls this reflection.
- It builds a
SELECTstatement from that metadata, limited to the columns you asked for. - It runs the statement and fetches the rows.
- It converts the result to a DataFrame, using the reflected column types to decide some conversions.
Step 1 explains the main restriction. A plain sqlite3 connection cannot reflect a table, so read_sql_table requires SQLAlchemy. The database driver can be anything SQLAlchemy supports.
Setting up sample data
The examples use the orders table from earlier chapters and add a shipments table. The new table has declared DATE and DATETIME column types, which let you see how reflection affects conversion. Run this once to create shop.db:
import sqlite3
conn = sqlite3.connect("shop.db")
conn.executescript("""
DROP TABLE IF EXISTS orders;
DROP TABLE IF EXISTS shipments;
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 shipments (
id INTEGER PRIMARY KEY,
order_id INTEGER,
shipped_on DATE,
shipped_at DATETIME
);
INSERT INTO shipments VALUES
(1, 1, '2024-01-06', '2024-01-06 14:30:00'),
(2, 2, '2024-01-10', '2024-01-10 09:15:00'),
(3, 3, NULL, NULL);
""")
conn.commit()
conn.close()The basic call
Create an engine and pass it with the table name:
import pandas as pd
from sqlalchemy import create_engine
engine = create_engine("sqlite:///shop.db")
orders = pd.read_sql_table("orders", engine)
print(orders)
print(orders.dtypes)You get every row and every column of orders. The id column is an ordinary column and the index is a default RangeIndex. The total column is float64. The created_at column holds text, because it was declared TEXT.
Recent pandas 2.x releases also accept a URL string such as "sqlite:///shop.db" as con. In that case pandas creates an engine for the call. Build the engine yourself if you make several calls, so you can reuse it.
Choosing columns and the index
Three parameters shape the result without any SQL:
columnsis a list of column names to fetch. Unselected columns are never transferred.index_colis a column name, or a list of names for aMultiIndex, to use as the index.coerce_float(defaultTrue) converts values such asDecimalto floating point.
orders = pd.read_sql_table(
"orders",
engine,
index_col="id",
columns=["customer", "total"],
)
print(orders) customer total
id
1 Ada 120.5
2 Grace 80.0
3 Ada 200.0id is not in columns, but the call still works. pandas adds the index_col columns to the SELECT for you, then moves them into the index. Naming the index column in columns as well is also fine.
Selecting only the columns you need matters most on wide tables. Fetching 5 of 80 columns reduces both the database work and the memory the DataFrame uses.
Dates and types
read_sql_table can convert types because it knows the declared type of each column. This is the main behavioral difference from read_sql_query, which has only the values to go on.
shipments = pd.read_sql_table("shipments", engine, index_col="id")
print(shipments.dtypes)shipped_on and shipped_at come back as datetime64 columns. The row with NULL values becomes NaT. You did not pass parse_dates, because SQLAlchemy reflected the declared DATE and DATETIME types and pandas converted them.
The created_at column in orders was declared TEXT, so pandas has no signal that it holds dates. Use parse_dates for that case:
orders = pd.read_sql_table(
"orders",
engine,
index_col="id",
parse_dates=["created_at"],
)
print(orders.dtypes)parse_dates accepts three forms:
| Form | Example | Meaning |
|---|---|---|
| List of names | `["created_at"]` | Parse each column with default settings |
| Dict of name to format | `{"created_at": "%Y-%m-%d"}` | Parse with an explicit `strftime` format |
| Dict of name to kwargs | `{"created_at": {"format": "%Y-%m-%d", "utc": True}}` | Pass the options to `pandas.to_datetime` |
An explicit format is faster and avoids ambiguity such as 03/04/2024 being read as March or April.
Reflection does not repair integer columns that contain NULL. A nullable integer column usually arrives as float64 with NaN, as it does with read_sql_query. Use astype("Int64") or dtype_backend="numpy_nullable" if you need integers to stay integers.
Selecting a schema
Databases such as PostgreSQL group tables into schemas. By default, pandas looks in the connection's default schema, which is public on PostgreSQL. To read a table from a different schema, pass schema:
orders = pd.read_sql_table("orders", engine, schema="main", index_col="id")
print(orders.shape)SQLite calls its default database main, so the call above works here. On PostgreSQL you would write something like schema="sales". Do not put the schema in the table name. "sales.orders" is treated as a single table name containing a dot, and pandas will not find it.
Reading in chunks
read_sql_table accepts chunksize, with the same meaning as in read_sql_query. The function then returns an iterator of DataFrames, each with at most chunksize rows.
total = 0.0
for chunk in pd.read_sql_table("orders", engine, index_col="id", chunksize=2):
print(len(chunk), "rows")
total += chunk["total"].sum()
print(total)The first chunk has two rows and the second has one. Chunking limits how much sits in pandas memory at once. It does not make the database do less work, and it does not let you filter rows. If you only need part of a large table, a query with a WHERE clause is the better tool.
What read_sql_table cannot do
The function takes a table name and nothing else, so it has no WHERE, JOIN, GROUP BY, ORDER BY or LIMIT, and it has no params argument. Every row of the table is transferred and every row ends up in memory. This is fine for a 500-row lookup table. It is a problem for a 200-million-row event table.
The same limit applies to what you can read:
- Joins and aggregations need
read_sql_query. - A view or other database object may not reflect on every backend.
read_sql_queryalways works for it. - Only a single table is read per call.
If you catch yourself loading a whole table and then filtering it in pandas, move the filter into SQL. The chapter on deciding what to do in SQL and what in pandas explains how to decide.
read_sql_table compared with read_sql_query
| Aspect | `read_sql_table` | `read_sql_query` |
|---|---|---|
| Input | Table name | SQL string, or a SQLAlchemy `text()` or other selectable |
| Accepted `con` | SQLAlchemy engine or connection (or URL string) | SQLAlchemy connectable or a DBAPI connection such as `sqlite3` |
| Filtering and joins | Not possible | Any SQL the database supports |
| Query parameters | None | `params` |
| Type information | Reflected declared types (for example `DATE`, `DATETIME`) | Values only; use `parse_dates` or `dtype` |
| Column subset | `columns` | Write them in `SELECT` |
| Schema | `schema` | Qualify names in the SQL |
| Extra database round trips | Reflection queries on each call | Only the query itself |
The last row is easy to overlook. Each call reflects the table again, so in a loop over many tables or many calls, the reflection overhead adds up. For one-off reads, it is negligible.
Reading several tables
A common pattern is loading a handful of small reference tables with one engine. Keep the engine in one place and reuse it:
from sqlalchemy import create_engine
import pandas as pd
engine = create_engine("sqlite:///shop.db")
try:
frames = {
name: pd.read_sql_table(name, engine, index_col="id")
for name in ["orders", "shipments"]
}
finally:
engine.dispose()
merged = frames["orders"].join(
frames["shipments"].set_index("order_id"),
how="left",
rsuffix="_shipment",
)
print(merged.columns.tolist())engine.dispose() closes the pooled connections when you are finished. This matters for a database server, where an idle pool holds server connections open. For a SQLite file it is a courtesy that also helps if you need to delete the file on Windows.
To find out which tables exist before reading them, use SQLAlchemy's inspector:
from sqlalchemy import create_engine, inspect
engine = create_engine("sqlite:///shop.db")
print(inspect(engine).get_table_names())This prints ['orders', 'shipments']. The list order can vary between backends, so sort it if you depend on it.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Error when passing a `sqlite3` connection | `read_sql_table` needs SQLAlchemy to reflect the table | Create an engine with `create_engine("sqlite:///file.db")` |
| `ImportError` mentioning SQLAlchemy | SQLAlchemy is not installed or is too old for your pandas | `pip install --upgrade sqlalchemy` |
| `ValueError: Table orders not found` | Wrong name, wrong schema, or wrong database file | Check `inspect(engine).get_table_names(schema=...)` and the engine URL |
| Empty database after `create_engine("sqlite:///x.db")` | SQLite creates a new empty file if the path is wrong; the relative path depends on the working directory | Print `os.getcwd()` or use an absolute path |
| Table found with one capitalization only | Some databases treat quoted identifiers as case-sensitive | Use the exact name that `get_table_names()` returns |
| `KeyError` for a name in `columns` or `index_col` | The column does not exist in the table | Compare against `inspect(engine).get_columns("orders")` |
| A date column still has text values | The column was declared `TEXT` or `VARCHAR`, so reflection gives no date type | Pass `parse_dates` |
| Out-of-memory error | The whole table was loaded | Use `chunksize`, `columns`, or a filtered `read_sql_query` |
Choosing between the two functions
Use read_sql_table when all of these hold:
- You want a whole table, or a column subset of it.
- The table is small enough to fit comfortably in memory, or you will process it in chunks.
- You already use SQLAlchemy, and you want declared date types converted automatically.
Use read_sql_query in every other case: when you need filters, joins, aggregation, parameters, a sqlite3 connection, or views. Chapter 9 introduces read_sql, which picks between the two based on whether you give it a table name or a query.
Exercise
You run pd.readsqltable("orders", engine, index_col="id", columns=["total"]). Which columns does the resulting DataFrame contain, and what is the index?
Show answer
The DataFrame has one column, total. The index is the id column. pandas adds the index_col column to the SELECT automatically, even though it is not listed in columns, and then moves it into the index.
Exercise
The shop.db file contains a table named events with a column occurredon declared as TEXT and holding values like 2024-03-15. After readsql_table("events", engine), the column has an object (text) dtype. Write the call that returns it as datetime64 values.
Show answer
pd.readsqltable("events", engine, parsedates={"occurredon": "%Y-%m-%d"}). Reflection sees TEXT, so it does not convert the column on its own. parsedates tells pandas to run todatetime on it, and the format makes parsing fast and unambiguous. The list form ["occurred_on"] also works.
Exercise
A colleague wants only the 2024 rows from a table with 100 million rows and calls readsqltable("orders", engine), then filters the DataFrame in pandas. Name two problems with this approach and the better function to use.
Show answer
First, every row is transferred from the database and held in memory before the filter runs, which is slow and can exhaust memory. Second, readsqltable has no way to push a WHERE clause to the database, and chunksize only splits the transfer without reducing it. Use readsqlquery with a WHERE clause on the date column, passing values through params.