Sub topic 7
Reading large results with chunksize
This chapter assumes you can run pd.read_sql_query against a sqlite3 connection or a SQLAlchemy engine. It also assumes you know how to pass params, and that you are comfortable with for loops and with blocks. Here you will learn how to process a query result that is too big to hold comfortably in memory, by reading it a piece at a time.
Why a large result is a problem
By default, read_sql_query runs the query, fetches every row, and builds one DataFrame. That DataFrame needs enough memory for all the rows at once. Pandas also uses more memory than the raw data. Text columns become Python objects, and a column with NULLs may switch to a wider dtype.
A query returning a few million rows can exhaust memory even when the database file is small. The chunksize argument changes the shape of the work. Instead of one DataFrame, you get a sequence of smaller DataFrames, each with at most chunksize rows. Your code handles one chunk, discards it, and moves to the next.
The examples below use a table of 100,000 events. Run this setup once.
import sqlite3
import pandas as pd
conn = sqlite3.connect("events.db")
conn.executescript("""
DROP TABLE IF EXISTS events;
CREATE TABLE events (
id INTEGER PRIMARY KEY,
user_id INTEGER,
kind TEXT,
amount REAL,
created_at TEXT
);
""")
kinds = ("view", "click", "buy")
rows = [
(
i,
i % 50,
kinds[i % 3],
None if i % 7 == 0 else (i % 100) / 4,
f"2024-01-{i % 28 + 1:02d}",
)
for i in range(1, 100_001)
]
conn.executemany("INSERT INTO events VALUES (?, ?, ?, ?, ?)", rows)
conn.commit()Every seventh row has a NULL amount. That detail matters later.
The basic pattern
Pass an integer as chunksize. The call then returns an iterator of DataFrames instead of one DataFrame.
chunks = pd.read_sql_query("SELECT * FROM events", conn, chunksize=25_000)
print(type(chunks))
for n, chunk in enumerate(chunks):
print(n, chunk.shape, chunk["id"].min(), chunk["id"].max())The loop prints four lines. Each chunk has 25,000 rows, and the last one ends at id 100000. If the row count is not an exact multiple of chunksize, the final chunk is smaller.
The returned object is an iterator, not a list. This has three consequences:
- You cannot call
len()on it or index it withchunks[0]. - You can loop over it only once. A second loop yields nothing.
- Rows are produced as you ask for them, so only the current chunk needs to be in memory on your side.
chunks = pd.read_sql_query("SELECT id FROM events", conn, chunksize=50_000)
print(sum(len(c) for c in chunks)) # 100000
print(sum(len(c) for c in chunks)) # 0, the iterator is already exhaustedWhat happens inside
The diagram shows the exchange between your code, pandas, and the database cursor. A cursor is the object a database driver uses to walk through a query result.
Two details follow from this model.
First, the query runs once. Chunking is not pagination with LIMIT and OFFSET. The database produces one result set, and pandas reads it in slices. Row order within that single execution is consistent, even if you did not write ORDER BY. If you need a specific order, say so in the query, but you do not need ORDER BY just to keep chunks from overlapping.
Second, the connection and cursor must stay open for the whole loop. Pandas calls fetchmany lazily, so every chunk after the first still needs the live cursor.
Keep the connection open while you iterate
The most common chunking bug is creating the iterator inside a with block and consuming it after the block has closed the connection.
from sqlalchemy import create_engine
engine = create_engine("sqlite:///events.db")
# Wrong: the connection closes before the loop runs.
with engine.connect() as connection:
chunks = pd.read_sql_query("SELECT * FROM events", connection, chunksize=10_000)
for chunk in chunks: # fails: the connection is already closed
print(len(chunk))Put the loop inside the block instead.
with engine.connect() as connection:
chunks = pd.read_sql_query("SELECT * FROM events", connection, chunksize=10_000)
for chunk in chunks:
print(len(chunk))The same rule applies when you wrap the chunking in a helper function. A function that returns the iterator and also closes the connection hands the caller a broken iterator. Either make the function a generator that yields chunks while it holds the connection, or let the caller own the connection.
def iter_events(engine, chunksize=10_000):
with engine.connect() as connection:
yield from pd.read_sql_query(
"SELECT * FROM events", connection, chunksize=chunksize
)
for chunk in iter_events(engine):
print(len(chunk))Reduce each chunk, then combine
Chunking only saves memory if each chunk is reduced to something small before you move on. If you collect every chunk in a list and call pd.concat, you hold the full result in memory again, plus the overhead of the pieces.
Totals and counts
Sums and counts combine across chunks directly.
total = 0.0
count = 0
for chunk in pd.read_sql_query("SELECT amount FROM events", conn, chunksize=10_000):
total += chunk["amount"].sum()
count += chunk["amount"].count()
print(total / count)sum() skips NaN values, and count() counts only non-null values. Together they give the same mean as computing it on the full column.
Do not average the per-chunk means. Chunks can contain different numbers of non-null values, and the last chunk is usually smaller, so the average of averages is wrong. Keep the sum and the count, and divide at the end.
Grouped partial results
For a group-by, aggregate each chunk, keep the small partial tables, and merge them.
partials = []
for chunk in pd.read_sql_query(
"SELECT kind, amount FROM events", conn, chunksize=10_000
):
partials.append(chunk.groupby("kind")["amount"].agg(["sum", "count"]))
result = pd.concat(partials).groupby(level=0).sum()
result["mean"] = result["sum"] / result["count"]
print(result)Each partial table has at most one row per kind, so memory use depends on the number of groups, not on the number of rows. This works for statistics that can be rebuilt from parts: sum, count, min, max, and mean (from sum and count). It does not work for a median or an exact distinct count, which need the full data or a different algorithm.
Filtering
If you need only some rows, filter each chunk and keep the survivors.
kept = []
for chunk in pd.read_sql_query("SELECT * FROM events", conn, chunksize=20_000):
kept.append(chunk[chunk["amount"] > 20])
big = pd.concat(kept, ignore_index=True)
print(len(big))This only helps if big is much smaller than the table. Even then, the filter belongs in the SQL when it can be expressed there, as the next section explains.
Writing results out
When the goal is to copy data somewhere else, write each chunk as you receive it.
first = True
query = "SELECT id, user_id, amount FROM events WHERE kind = 'buy'"
for chunk in pd.read_sql_query(query, conn, chunksize=10_000):
chunk.to_csv(
"buys.csv",
mode="w" if first else "a",
header=first,
index=False,
)
first = FalseThe first chunk creates the file with a header. Later chunks append rows without repeating the header. Memory use stays flat however large the table is.
Chunking is not a replacement for pushing work into SQL
Chunking handles the case where the rows you need cannot fit in memory. It does not make the transfer cheaper. Every row you select still travels from the database to Python. If a GROUP BY in SQL can return 50 rows instead of streaming 100,000, the SQL version is faster and simpler.
| Situation | Better choice |
|---|---|
| Aggregate that SQL can compute (sum, count, group-by) | Aggregate in SQL, no chunking |
| Filter that SQL can express | Add a `WHERE` clause, no chunking |
| Result fits in memory | Plain `read_sql_query` |
| Result is too large, and pandas logic is needed per row or per chunk | `chunksize` |
| Copying a large table to a file or another system | `chunksize`, writing each chunk |
| Statistic that cannot be built from partial results | Compute it in SQL, or sample |
A practical order is to select only the columns you need, filter in SQL, aggregate in SQL if possible, and use chunking for what remains.
Dtypes and the index across chunks
Each chunk is its own DataFrame, and pandas infers dtypes for each one separately. This produces several gotchas.
NULLs can change dtypes between chunks. An integer column with no NULLs in chunk 1 is int64. The same column with one NULL in chunk 2 becomes float64, because plain NumPy integers cannot hold missing values. Concatenating the chunks then gives a float column. In the events table, amount is always float, but a nullable integer column would show this problem. Request a nullable dtype explicitly so every chunk agrees.
chunks = pd.read_sql_query(
"SELECT id, user_id, kind, amount, created_at FROM events",
conn,
chunksize=25_000,
index_col="id",
parse_dates=["created_at"],
dtype={"user_id": "int32"},
)
for chunk in chunks:
print(chunk.dtypes.to_dict())
breakindex_col, parse_dates, and dtype all apply to every chunk. Use Int64 (capital I) for an integer column that may contain NULLs, and parse_dates for any text date column, so each chunk converts dates the same way.
The index restarts in each chunk. Without index_col, every chunk gets its own RangeIndex starting at 0. When you concatenate chunks, pass ignore_index=True to get a clean index, or use index_col so the index comes from a real key.
Category columns can differ. If you convert a column to category per chunk, each chunk only knows the values it contains. Concatenating categoricals with different category sets falls back to object. Convert after combining, or fix the categories up front with pd.CategoricalDtype.
Choosing a chunk size
There is no universal best value. A few rules of thumb help:
- Very small chunks, such as 100 rows, spend most of the time on per-chunk overhead: a driver call, building a DataFrame, and your loop body.
- Very large chunks lose the memory benefit.
- For typical tables, values from 10,000 to 100,000 rows are reasonable starting points.
- Estimate memory per chunk with
chunk.memory_usage(deep=True).sum()on the first chunk, then scalechunksizeso one chunk uses a fraction of your available memory. Text-heavy rows are much larger than numeric rows.
first_chunk = next(
pd.read_sql_query("SELECT * FROM events", conn, chunksize=1_000)
)
print(first_chunk.memory_usage(deep=True).sum() / 1_000, "bytes per row")When the driver still loads everything
Passing chunksize to pandas controls how pandas slices the result. It does not guarantee that the database driver avoids loading the entire result first.
- With
sqlite3, rows are fetched as requested, so chunking really does limit memory. - Some drivers, such as
psycopg2for PostgreSQL, use client-side cursors by default. The whole result is transferred to the Python process when the query executes, and pandas then slices it. Your peak memory is the full result, even though your DataFrames are small.
For those drivers, ask SQLAlchemy for a streaming (server-side) cursor with the stream_results execution option.
from sqlalchemy import create_engine, text
import pandas as pd
engine = create_engine("sqlite:///events.db")
with engine.connect().execution_options(stream_results=True) as connection:
for chunk in pd.read_sql_query(
text("SELECT * FROM events WHERE kind = :kind"),
connection,
params={"kind": "buy"},
chunksize=5_000,
):
print(len(chunk))For SQLite this option makes no difference, so the example runs anywhere. On a driver that supports server-side cursors, it keeps the result on the database server and sends it in batches. Check your driver's documentation for the exact behavior, because support and side effects (such as an open transaction while you iterate) vary.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Loop body never runs on a second pass | The iterator was already consumed | Recreate it by calling `read_sql_query` again |
| Error about a closed connection or cursor while iterating | The connection closed before the loop ran | Loop inside the `with` block, or use a generator that holds the connection |
| `TypeError: object of type 'generator' has no len()` | Treating the iterator as a list | Loop over it, or count rows as you go |
| Memory still grows | You are appending whole chunks to a list, or the driver buffers everything | Reduce each chunk first, or use `stream_results=True` |
| An integer column becomes float in some chunks | NULLs appear in only some chunks | Pass `dtype={"col": "Int64"}` |
| Duplicate index values after `concat` | Each chunk restarts at 0 | Use `ignore_index=True` or `index_col` |
| Wrong overall mean | Averaged the per-chunk means | Keep sum and count, divide at the end |
Exercise
Write a loop that uses chunksize=10_000 to find the largest amount for each kind in the events table without ever holding more than one chunk of raw rows. Explain why the combine step uses max and not a mean.
Show answer
Compute a partial max per kind for each chunk, then take the max of the partials: partials = [] for chunk in pd.readsqlquery("SELECT kind, amount FROM events", conn, chunksize=10_000): partials.append(chunk.groupby("kind")["amount"].max()) result = pd.concat(partials).groupby(level=0).max() print(result) The maximum of the whole table is the maximum of the per-chunk maxima, so max can be rebuilt from partial results. A mean cannot be rebuilt from per-chunk means, because chunks can hold different numbers of non-null rows. In practice, a single SQL query with SELECT kind, MAX(amount) FROM events GROUP BY kind is simpler and faster, so chunking is only justified if other per-chunk pandas logic is needed.
Exercise
A colleague writes a function that opens a connection in a with block, calls pd.readsqlquery(..., chunksize=5000) inside it, and returns the result. Callers get an error when they loop over it. What is wrong, and how would you fix it?
Show answer
The function returns the iterator, and the with block closes the connection on return. Pandas fetches each chunk lazily from the open cursor, so the first fetch after the function returns fails. Fix it by making the function a generator that holds the connection while it yields: put "yield from pd.readsqlquery(..., chunksize=5000)" inside the with block. Alternatively, have the caller open the connection and pass it in, so the caller controls its lifetime.
Exercise
You chunk a table and pandas shows user_id as int64 in the first chunk and float64 in the third. What happened, and what argument prevents it?
Show answer
The third chunk contains at least one NULL in userid. A NumPy int64 column cannot hold missing values, so pandas stored that chunk as float64 with NaN. Passing dtype={"userid": "Int64"} to readsqlquery makes every chunk use the nullable integer type, so all chunks have the same dtype and NULLs become <NA>.