Sub topic 6
Deciding what to do in SQL and what in pandas
This chapter assumes you can run pd.read_sql_query against a connection and pass params, as covered in the earlier chapters. You should also know GROUP BY and the pandas groupby method.
The core trade-off
read_sql_query sends your SQL to the database. The database runs it and returns the result rows, and pandas builds a DataFrame from them. Work you put in the SQL happens inside the database, close to the data. Work you put after the call happens in your Python process, on whatever rows were transferred.
Moving work into SQL is often called pushdown. It pays off for two reasons:
- Fewer rows and columns cross the connection, so less time is spent on transfer and on building Python objects.
- The database can use indexes and its query planner. pandas always scans what it has in memory.
Pushdown is not always the right choice. The sections below give rules for each side.
Aggregating: transfer rows or transfer answers
The two approaches below produce the same numbers. The first loads every row and aggregates in pandas. The second aggregates in the database.
import sqlite3
import pandas as pd
conn = sqlite3.connect(":memory:")
conn.executescript("""
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');
""")
# Pandas side: every row is transferred, then grouped in memory
everything = pd.read_sql_query("SELECT * FROM orders", conn)
in_pandas = everything.groupby("customer", as_index=False)["total"].sum()
# SQL side: the database groups, only one row per customer is transferred
in_sql = pd.read_sql_query(
"SELECT customer, SUM(total) AS revenue FROM orders GROUP BY customer",
conn,
)
print(in_pandas)
print(in_sql)With three rows the difference is invisible. With 50 million orders and 2,000 customers, the second query transfers 2,000 rows instead of 50 million.
Filtering and selecting columns
Apply the same idea before aggregation. Filter with WHERE and list only the columns you need, instead of using SELECT * and then calling df[df["total"] > 100].
recent = pd.read_sql_query(
"SELECT customer, total, created_at FROM orders WHERE created_at >= ?",
conn,
params=("2024-01-01",),
parse_dates=["created_at"],
)
print(recent.dtypes)Keep values in params, as you did in the earlier chapter on parameters. Do not build the filter with string formatting.
When pandas is the better place
SQL is not always the better tool. Use pandas when:
- You will reuse the data. If you will slice the same result five ways, fetch it once with a coarse filter. Five separate queries cost five round trips and five times the database load.
- The operation is awkward in SQL. Examples are rolling windows, pivots, reshaping, plotting, and statistics such as the median, which SQLite has no built-in function for.
- You need to combine the result with non-database data, such as a CSV file or an API response.
- The database is shared and busy. Heavy aggregation on a production server can slow other users. A simple
SELECTwith a filter, followed by work in pandas, can be the kinder option.
This example fetches a filtered slice once and then derives monthly totals in pandas:
monthly = recent.groupby(recent["created_at"].dt.to_period("M"))["total"].sum()
print(monthly)A decision flow
A practical rule: shrink the data in SQL, then shape and analyze it in pandas.
Gotchas when moving work between the two
Identical-looking operations can give different results.
| Situation | SQL behavior | pandas behavior |
|---|---|---|
| `SUM` of a column that is all NULL | Returns NULL | `sum()` returns `0.0` by default |
| NULL in a grouping column | Rows form their own group | `groupby` drops them unless `dropna=False` |
| Integer division | Many databases truncate (`5 / 2` gives `2`) | `/` always gives a float |
| Text comparison and sorting | Depends on the database collation | Compares by Unicode code point |
Dialect differences also matter. A date function written for PostgreSQL will fail on SQLite. Pushdown ties your code to one database, while pandas code runs unchanged anywhere.
Summary of the rules
- Filter rows with
WHEREand choose columns in theSELECTlist. - Aggregate in SQL when you only need the summary.
- Fetch once and finish in pandas when you will explore the data repeatedly or need operations SQL handles poorly.
- Check NULL handling and data types whenever you move a calculation from one side to the other.
Exercise
A table has 80 million rows. You need the average total per customer, and the result is only used to draw one bar chart. Which side should compute the average, and why? Name one result difference to check if you compare it with a pandas calculation.
Show answer
Compute it in SQL with SELECT customer, AVG(total) AS avg_total FROM orders GROUP BY customer. The aggregation shrinks 80 million rows to one row per customer before transfer, and the result is used only once, so there is no reason to load the raw rows. When comparing with pandas, check NULL handling: both AVG and mean() skip NULLs, but a customer whose totals are all NULL gets NULL from SQL and NaN from pandas, and grouping on a NULL customer value behaves differently (pandas drops it by default).