Sub topic 12
Chunked Reads from SQL, JSON Lines and Parquet
This chapter assumes you can already read a CSV in chunks with chunksize, combine partial results across chunks, and write output incrementally. The same ideas apply to other sources. What changes is the function you call and the options it offers. You will see how to read in pieces from a SQL database, a JSON Lines file and a Parquet file, and where each approach has limits.
The pattern stays the same
Every chunked workflow has three parts:
- Open a source that yields pieces.
- Reduce or filter each piece to something small.
- Combine the small results, or write them out as you go.
Only step 1 differs between formats. Steps 2 and 3 are the code you have already written for CSV files.
SQL: read_sql with chunksize
pandas.read_sql and pandas.read_sql_query accept a chunksize argument. When you set it, the call returns an iterator of DataFrames instead of one large DataFrame. The following example uses SQLite from the standard library, so it runs without a database server.
import sqlite3
import pandas as pd
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE sales (region TEXT, amount REAL)")
rows = [("north", 10.0), ("south", 20.0), ("north", 30.0), ("east", 5.0), ("south", 15.0)]
conn.executemany("INSERT INTO sales VALUES (?, ?)", rows)
conn.commit()
totals = None
for chunk in pd.read_sql_query("SELECT region, amount FROM sales", conn, chunksize=2):
part = chunk.groupby("region")["amount"].agg(["sum", "count"])
totals = part if totals is None else totals.add(part, fill_value=0)
totals["mean"] = totals["sum"] / totals["count"]
print(totals)
conn.close()The loop body is the same as in the CSV aggregation example. Each chunk is reduced to per-region sums and counts, and the partial results are added together.
Where the work really happens
Pushing work into the database is often better than chunking in pandas. A database can compute SUM(amount) ... GROUP BY region close to the data, using indexes, and return a handful of rows. Use chunking when you need the raw rows in Python, for example to apply a function SQL cannot express, or to export a filtered table to a file.
A caveat about server-side cursors
Setting chunksize does not always mean the database sends rows in small batches. With some drivers, the client library fetches the whole result set into local memory first, and pandas only slices it afterwards. You would then run out of memory before the first chunk arrives.
Whether this happens depends on the driver:
- SQLite fetches rows lazily, so chunking helps.
- PostgreSQL through psycopg2 downloads the whole result by default. A server-side cursor avoids this.
- MySQL drivers have similar buffering defaults.
With SQLAlchemy, you can request streaming at the connection level:
import pandas as pd
from sqlalchemy import create_engine, text
engine = create_engine("sqlite:///example.db")
with engine.connect().execution_options(stream_results=True) as conn:
query = text("SELECT region, amount FROM sales")
for chunk in pd.read_sql_query(query, conn, chunksize=50_000):
print(len(chunk))stream_results=True asks the driver to use a server-side cursor where it supports one. Check your driver's documentation and watch memory use on a real run before you trust it.
Filter in the query, not in pandas
Select only the columns you need, and add a WHERE clause for any filter you can express in SQL. This is the database version of usecols. Transferring less data is faster and uses less memory than fetching everything and discarding it in each chunk.
JSON Lines: read_json with lines and chunksize
JSON Lines (also called NDJSON) stores one JSON object per line. Because each line is a complete record, the file can be split at any line boundary, which makes it suited to chunking. A regular JSON file holding one large array has no such boundaries, and pandas has to parse it as a whole.
Pass lines=True and chunksize to read_json. You get an iterator, which you can use as a context manager.
import io
import pandas as pd
data = "\n".join(
[
'{"user": "a", "status": "ok", "ms": 120}',
'{"user": "b", "status": "error", "ms": 900}',
'{"user": "c", "status": "ok", "ms": 80}',
'{"user": "d", "status": "error", "ms": 450}',
'{"user": "e", "status": "ok", "ms": 95}',
]
)
error_count = 0
with pd.read_json(io.StringIO(data), lines=True, chunksize=2) as reader:
for chunk in reader:
error_count += (chunk["status"] == "error").sum()
print(error_count)The output is 2. In a real job you would pass a file path instead of io.StringIO(data).
Some points to keep in mind:
chunksizeonly works together withlines=True. Without it, pandas raises an error.- Each chunk is parsed independently, so dtypes are inferred per chunk. A column that looks like integers in one chunk and has missing values in the next can change dtype. Pass
dtype=to fix it, as you did for CSV. - The index of each chunk continues from the previous one, as with
read_csv. - Malformed lines raise an error for the chunk that contains them. Clean the file first if you cannot trust it.
Parquet: batches with pyarrow
Parquet is a columnar binary format. Unlike CSV, it stores column data in compressed blocks called row groups, together with a schema, so dtypes do not drift between pieces. pandas.read_parquet has no chunksize option, so you read in batches through pyarrow instead.
import pyarrow.parquet as pq
pf = pq.ParquetFile("big.parquet")
for batch in pf.iter_batches(batch_size=100_000):
df = batch.to_pandas()
print(len(df))iter_batches yields RecordBatch objects. Calling to_pandas() on each one gives a DataFrame that you can process with the same code you used for CSV chunks.
Reading fewer columns
Parquet is columnar, so reading a subset of columns skips the others entirely on disk. This is stronger than usecols in CSV, where the parser still has to scan every line.
import pyarrow.parquet as pq
pf = pq.ParquetFile("big.parquet")
total = 0.0
for batch in pf.iter_batches(batch_size=100_000, columns=["amount"]):
total += batch.to_pandas()["amount"].sum()
print(total)Row groups and batch size
A Parquet file is divided into row groups, and pf.metadata.num_row_groups reports how many. The file is decompressed one row group at a time, so very large row groups raise the memory floor no matter what batch_size you choose. If you write Parquet files yourself, pick a row group size that fits comfortably in memory, for example a few hundred thousand to a few million rows.
You can also read one row group at a time with pf.read_row_group(i). This is useful when you want to process or retry specific parts of a file.
Comparing the sources
| Source | Function | Chunk option | Dtypes between chunks | Main limit |
|---|---|---|---|---|
| CSV | `pd.read_csv` | `chunksize` | Inferred per chunk | Parsing speed |
| SQL | `pd.read_sql_query` | `chunksize` | Set by the database types | Driver may buffer all rows |
| JSON Lines | `pd.read_json(lines=True)` | `chunksize` | Inferred per chunk | Text parsing, no column skipping |
| Parquet | `pyarrow.parquet.ParquetFile` | `iter_batches(batch_size=...)` | Fixed by the file schema | Row group size sets minimum memory |
Writing results back out
The incremental writing pattern carries over. You can append filtered chunks to a CSV as before. For Parquet output, write with pyarrow.parquet.ParquetWriter, which keeps one file open and appends row groups as you go.
import pyarrow as pa
import pyarrow.parquet as pq
writer = None
pf = pq.ParquetFile("big.parquet")
try:
for batch in pf.iter_batches(batch_size=100_000):
df = batch.to_pandas()
errors = df[df["status"] == "error"]
table = pa.Table.from_pandas(errors, preserve_index=False)
if writer is None:
writer = pq.ParquetWriter("errors.parquet", table.schema)
writer.write_table(table)
finally:
if writer is not None:
writer.close()Closing the writer matters. A Parquet file stores its footer at the end, and a file that was never closed cannot be read. The try/finally block makes sure the footer is written even if the loop fails.
One more gotcha: if every row in the first chunk is filtered out, the schema of that empty table may not match later chunks, for example when a column of strings is inferred as an object with no values. Fix the schema ahead of time with pf.schema_arrow if your data has columns that can be empty.
Common mistakes
- Assuming
read_sqlwithchunksizestreams from the server, then running out of memory on the first fetch. - Forgetting
lines=Truewhen usingchunksizewithread_json. - Calling
pd.read_parquet(..., chunksize=...). The function does not accept it. - Not closing a
ParquetWriter, which leaves an unreadable file. - Using SQL chunks for aggregation that the database could do in one query.
Exercise
You need the total of the "amount" column in a 20 GB Parquet file, and you want to keep memory use low. Which approach do you use, and why is it better than reading the whole file with pd.read_parquet?
Show answer
Open the file with pyarrow.parquet.ParquetFile and loop over iterbatches(batchsize=100000, columns=["amount"]). Convert each batch with topandas(), add its sum to a running total, and print the total at the end. Only one batch of one column is in memory at a time. pd.read_parquet would load every row, and every column unless you pass columns, into one DataFrame.
Exercise
A colleague runs pd.readsqlquery("SELECT * FROM events", pgconn, chunksize=10000) against a PostgreSQL table with 300 million rows using psycopg2, and the process runs out of memory before the first chunk is returned. What is the likely cause, and what are two ways to reduce the problem?
Show answer
The driver downloads the entire result set into client memory before pandas slices it into chunks, so chunksize does not help. Two fixes are to use a server-side cursor, for example with SQLAlchemy executionoptions(streamresults=True), and to reduce the data in the query by selecting only the needed columns and adding a WHERE clause or doing the aggregation in SQL.