Sub topic 3
Reading Large Results with `chunksize`
Assume you know basic Python, pandas DataFrames, and SQL SELECT queries. This chapter focuses on choosing a safe way to load large query results.
Reading large results with `chunksize`
Without chunksize, read_sql_query returns one DataFrame and keeps the complete result in memory. With chunksize, it returns an iterator of smaller DataFrames, called chunks.
import pandas as pd
total_revenue = 0.0
for chunk in pd.read_sql_query(
"SELECT customer, total FROM orders",
conn,
chunksize=1000,
):
total_revenue += chunk["total"].sum()
print(total_revenue)Each chunk supports normal pandas operations. You can filter, aggregate, or write it to another destination before loading the next chunk.
chunksize reduces pandas memory usage, but the database still executes the query. Add useful WHERE conditions and select only required columns.
Loading whole tables with `read_sql_table`
Use read_sql_table when you want a table rather than a custom query. It requires a SQLAlchemy engine.
from sqlalchemy import create_engine
engine = create_engine("sqlite:///shop.db")
orders = pd.read_sql_table(
"orders",
engine,
index_col="id",
columns=["customer", "total"],
)This function cannot express arbitrary filtering as directly as SQL. Use read_sql_query when you need joins, grouping, or complex conditions.
Using `read_sql` as a single entry point
pd.read_sql dispatches to a query or table reader. Pass a SQL query string to read query results, or pass a table name to load a table.
orders = pd.read_sql("SELECT * FROM orders", engine)This is convenient when the input may change, but the explicit functions make your intent clearer.
Diagnosing common errors and warnings
| Problem | Likely cause | Fix |
|---|---|---|
| Unsupported connection warning | A raw driver connection is not fully supported | Use SQLAlchemy, or use `sqlite3` for SQLite |
| Parameter style error | Placeholder syntax does not match the driver | Use `?` with `sqlite3`, or named parameters with SQLAlchemy |
| Memory error | The result is too large | Select fewer columns, filter in SQL, or use `chunksize` |
Exercise
What should you change when a query result is too large for memory?
Show answer
Filter or aggregate in SQL, select fewer columns, or process the result with chunksize.