Sub topic 8
Loading whole tables with read_sql_table
This chapter assumes you can run read_sql_query against a SQLAlchemy engine and that you know what index_col and parse_dates do. If not, review the earlier chapters on connections and type handling first.
What read_sql_table does
pandas.read_sql_table loads a table by name. You pass a table name instead of a SQL string, and pandas builds the SELECT for you.
It does this in three steps. It inspects the table's structure through SQLAlchemy, which is called reflection. It generates a query for the columns you asked for. It then fetches the rows into a DataFrame.
flowchart TDUse the following diagram instead of the line above.
A first example
The setup block below creates the shop.db file used in earlier chapters, so you can run this on its own.
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()
conn.close()
engine = create_engine("sqlite:///shop.db")
orders = pd.read_sql_table("orders", engine)
print(orders)
print(orders.dtypes)All three rows and all four columns come back. created_at has dtype object because SQLite stores it as TEXT, and reflection finds no date type to use.
A SQLAlchemy connectable is required
read_sql_table needs SQLAlchemy because it relies on reflection. You can pass an engine or a SQLAlchemy connection. A plain sqlite3 connection raises an error instead of working.
Selecting columns, the index and dates
The main arguments are listed below.
| Argument | Purpose |
|---|---|
| `table_name` | Name of the table to read |
| `con` | SQLAlchemy engine or connection |
| `schema` | Schema that holds the table, for databases that use schemas |
| `index_col` | Column or list of columns to use as the index |
| `columns` | List of column names to fetch |
| `parse_dates` | Columns to convert to datetime |
| `coerce_float` | Convert decimal-like values to floats |
| `chunksize` | Return an iterator of DataFrames |
import pandas as pd
from sqlalchemy import create_engine
engine = create_engine("sqlite:///shop.db")
orders = pd.read_sql_table(
"orders",
engine,
index_col="id",
columns=["customer", "total", "created_at"],
parse_dates=["created_at"],
)
print(orders)
print(orders.dtypes)The id column does not appear in columns, but it still arrives as the index. Pandas adds the index_col columns to the query for you. created_at becomes datetime64[ns]. If the column were declared as a DATETIME type in the database, reflection would parse it without parse_dates.
Selecting columns reduces the data the database sends, so name only the columns you need.
What it cannot do
read_sql_table has no WHERE, JOIN, GROUP BY or params. It always reads every row of the table. It also has no dtype argument, so convert types afterwards with astype.
import pandas as pd
from sqlalchemy import create_engine
engine = create_engine("sqlite:///shop.db")
orders = pd.read_sql_table("orders", engine, index_col="id")
orders = orders.astype({"customer": "string"})
big_orders = orders[orders["total"] >= 100]
print(big_orders)This code reads the whole table and filters in pandas. That is fine for small tables. On a large table, the database sends rows you then discard. The earlier chapter on pushdown covers when to switch to read_sql_query with a WHERE clause.
Reading in chunks
read_sql_table accepts chunksize and returns an iterator of DataFrames, as read_sql_query does.
import pandas as pd
from sqlalchemy import create_engine
engine = create_engine("sqlite:///shop.db")
total = 0.0
for chunk in pd.read_sql_table("orders", engine, chunksize=2):
total += chunk["total"].sum()
print(total)Choosing between the two functions
| Situation | Better choice |
|---|---|
| Small lookup table, you want every row | `read_sql_table` |
| You want rows matching a condition | `read_sql_query` |
| You need a join or aggregate | `read_sql_query` |
| You only have a `sqlite3` connection | `read_sql_query` |
| You need `params` or `dtype` | `read_sql_query` |
Common mistakes
- Using a
sqlite3connection. This raisesNotImplementedError. Switch to an engine. - Misspelling the table name. Reflection fails with a
ValueErrorsaying the table was not found. Table names can be case-sensitive in some databases. - Forgetting
schema. A table in a non-default schema is not found unless you passschema="name". - Expecting dates to parse on their own. Columns stored as text stay as
objectuntil you passparse_dates.
Exercise
You have a SQLAlchemy engine and a table orders with columns id, customer, total and created_at (stored as text). Write a read_sql_table call that returns only customer and total, uses id as the index, and returns created_at as a datetime column. Then explain why the call needs one extra step if you also want to keep only rows with total >= 100.
Show answer
pd.readsqltable("orders", engine, indexcol="id", columns=["customer", "total", "createdat"], parsedates=["createdat"]) returns the index, the two requested columns and the parsed date column. Note that created_at must be listed in columns, or it is not fetched and cannot be parsed. Filtering needs a second step because readsqltable has no WHERE clause or params. You filter afterwards with df[df["total"] >= 100], or you switch to readsqlquery with a WHERE clause so the database filters the rows.