Sub topic 7
Reading large results with chunksize
This chapter assumes you can run read_sql_query against a sqlite3 connection or a SQLAlchemy engine, and that you know basic pandas aggregation. It uses the shop.db database with the orders table from the earlier chapters.
The memory problem
By default, read_sql_query fetches every row of the result and builds one DataFrame. If the query returns 50 million rows, pandas needs enough memory for all of them at once.
The chunksize argument changes the return value. Instead of a DataFrame, you get an iterator that yields DataFrames of at most chunksize rows each. Your code handles one piece, discards it, and moves on.
Correction: the diagram must use the required fence format. Here it is in full.
A first chunked loop
This script is self-contained. It rebuilds the table and reads it two rows at a time.
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()
total = 0.0
for chunk in pd.read_sql_query("SELECT * FROM orders", conn, chunksize=2):
print(len(chunk), "rows")
total += chunk["total"].sum()
print(total)The output shows a chunk of 2 rows, then a chunk of 1 row, then the total, 400.5. The last chunk is smaller because only one row is left.
Every other argument still works per chunk. params, index_col, parse_dates and dtype are applied to each chunk the same way.
Combining partial results
Each chunk sees only part of the data, so you must combine results in a way that stays correct. A sum can be added across chunks. An average cannot, so keep the sum and the count and divide at the end.
This example computes revenue per customer across chunks:
revenue = pd.Series(dtype="float64")
for chunk in pd.read_sql_query("SELECT customer, total FROM orders", conn, chunksize=2):
partial = chunk.groupby("customer")["total"].sum()
revenue = revenue.add(partial, fill_value=0)
print(revenue)add(..., fill_value=0) treats a customer missing from one side as 0. Without it, a customer who appears in only one chunk would become NaN.
The pattern is the same for any result: reduce each chunk to something small, then merge the small results. A related mistake is collecting every chunk in a list and calling pd.concat at the end. That rebuilds the full DataFrame in memory and removes the benefit of chunking.
What chunksize does not guarantee
Chunking limits how much pandas holds at once. It does not always limit what the database driver holds.
- With
sqlite3, the cursor fetches rows lazily, so memory use stays close to one chunk. - With some drivers, such as
psycopg2for PostgreSQL, the default cursor downloads the entire result to the client before pandas sees the first chunk. Memory is still spent, just outside pandas.
With SQLAlchemy you can ask for a streaming cursor using the stream_results execution option:
from sqlalchemy import create_engine, text
import pandas as pd
engine = create_engine("sqlite:///shop.db")
with engine.connect().execution_options(stream_results=True) as connection:
for chunk in pd.read_sql_query(
text("SELECT * FROM orders"), connection, chunksize=2
):
print(chunk["total"].sum())SQLite ignores the option because its cursors are already lazy. On PostgreSQL or MySQL drivers that support server-side cursors, it keeps the rows on the server until requested.
Pitfalls
- Dtypes can differ between chunks. pandas infers types per chunk. An integer column that contains
NULLin only one chunk becomesfloat64there and staysint64elsewhere. Setdtypeexplicitly, or convert inside the loop, when the types matter. - Chunk size is a trade-off. Very small chunks make many round trips and add overhead. Very large chunks use more memory. Start with 10,000 to 100,000 rows and adjust by measuring.
- Order is not guaranteed. Without
ORDER BY, the database may return rows in any order. If your logic depends on order, say so in the query. - Try SQL first. If you only need totals, counts or filtered rows, let the database do that work, as in the earlier chapter on SQL versus pandas. Chunking is for cases where you really need the detailed rows in Python.
Summary table
| Situation | Approach |
|---|---|
| Result fits in memory | Plain `read_sql_query`, no `chunksize` |
| Need only totals or groups | Aggregate in SQL |
| Large detailed result, need row-level work | `chunksize` and combine small partial results |
| Large result on a client-side cursor driver | `chunksize` with `stream_results=True` on the SQLAlchemy connection |
Exercise
You loop over pd.read_sql_query("SELECT customer, total FROM orders", conn, chunksize=2) and want the average order total across the whole table. Why is averaging each chunk's mean wrong, and what should you accumulate instead?
Show answer
The chunks can have different sizes (the last one is often smaller), so an average of chunk means gives the wrong weight to each row. Accumulate the running sum of total and the running row count (len(chunk)) across chunks, then divide the sum by the count after the loop.
Exercise
A loop over chunks from PostgreSQL still uses as much memory as loading the whole table at once. What is the likely cause, and how can you address it with SQLAlchemy?
Show answer
The driver's default cursor downloads the entire result to the client before pandas yields the first chunk. Open the connection with engine.connect().execution_options(stream_results=True) so the driver uses a server-side cursor, and keep that connection open while you iterate.