Sub topic 6
Deciding what to do in SQL and what in pandas
Every query you run with read_sql_query splits the work between two engines. The database can filter, group and sort next to the data. pandas can reshape, plot and model once the rows are in memory. This chapter gives you a working model for choosing where each step runs, and it covers the places where the two engines give different answers to the same question.
This chapter assumes you can write SELECT ... WHERE ... GROUP BY queries, that you know basic DataFrame operations such as groupby and boolean masks, and that you have already used pd.read_sql_query with a connection and params.
The working model: pay for what crosses the connection
A read_sql_query call has three stages:
- The database executes the SQL and produces a result set.
- The driver sends every row of that result set to Python, one tuple at a time.
- pandas builds a DataFrame from those tuples and infers column types.
Stage 2 and stage 3 cost time and memory in proportion to the number of rows and columns in the result set. They do not depend on the size of the table. Filtering or aggregating in SQL is called pushdown: you push the work down to the database so that fewer rows cross the connection.
The database has two other advantages. It can use indexes, so it may read only a small part of the table. It also works on typed, stored data, so it does not need to convert every value into a Python object.
pandas has its own strengths. You can run Python functions, chain many exploratory steps without a round trip per step, and combine the data with files, APIs or other databases.
A small dataset with awkward values
The examples use a table that includes NULL values, because NULLs are where SQL and pandas behave differently.
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'),
(4, 'Linus', NULL, '2024-02-03'),
(5, NULL, 45.0, '2024-02-10');
""")Filter and select columns in SQL
Filtering after loading is the most common waste. This code transfers all rows and columns and then discards most of them:
everything = pd.read_sql_query("SELECT * FROM orders", conn)
big_in_pandas = everything[everything["total"] >= 100]The same result with pushdown:
big_in_sql = pd.read_sql_query(
"SELECT id, customer, total FROM orders WHERE total >= ?",
conn,
params=(100,),
)
print(big_in_sql)Two things changed. The WHERE clause means fewer rows leave the database, and naming columns instead of SELECT * means fewer columns leave it. Wide tables often hold text or JSON columns you do not need, and those are expensive to transfer.
Always pass the filter values through params, even when you are only filtering. The previous chapter covered why. The next section shows how to build a filter dynamically without giving up that safety.
Building optional filters
When a function accepts optional filters, assemble the WHERE clause from fixed text fragments and collect the values separately:
def load_orders(conn, customer=None, min_total=None):
clauses = []
params = []
if customer is not None:
clauses.append("customer = ?")
params.append(customer)
if min_total is not None:
clauses.append("total >= ?")
params.append(min_total)
where = f"WHERE {' AND '.join(clauses)}" if clauses else ""
sql = f"SELECT id, customer, total FROM orders {where}"
return pd.read_sql_query(sql, conn, params=params)
print(load_orders(conn, customer="Ada", min_total=150))The f-string only inserts SQL fragments that you wrote in the code. User-supplied values never enter the string. They travel in params.
Make filters able to use an index
An index lets the database find matching rows without scanning the whole table. A filter can lose that benefit if you wrap the indexed column in a function. SQLite can describe its plan with EXPLAIN QUERY PLAN:
conn.execute("CREATE INDEX idx_orders_created ON orders(created_at)")
queries = [
"SELECT id FROM orders WHERE created_at >= '2024-02-01'",
"SELECT id FROM orders WHERE substr(created_at, 1, 7) = '2024-02'",
]
for sql in queries:
print(conn.execute("EXPLAIN QUERY PLAN " + sql).fetchall())The first plan normally reports a SEARCH that uses the index. The second reports a SCAN of the whole table, because the database must evaluate substr on every row. Rewrite the second filter as a range, created_at >= '2024-02-01' AND created_at < '2024-03-01', and the index works again. Other databases have their own commands, such as EXPLAIN in PostgreSQL and MySQL.
Aggregate in SQL when you only need the summary
If the final output is one row per group, let the database group. The result set has one row per customer instead of one row per order:
by_customer_sql = pd.read_sql_query(
"""
SELECT customer, SUM(total) AS revenue, COUNT(*) AS orders
FROM orders
GROUP BY customer
ORDER BY customer
""",
conn,
)
print(by_customer_sql)The pandas version loads the detail rows first:
everything = pd.read_sql_query("SELECT * FROM orders", conn)
by_customer_pandas = (
everything.groupby("customer")
.agg(revenue=("total", "sum"), orders=("id", "count"))
.reset_index()
)
print(by_customer_pandas)On five rows the difference does not matter. On fifty million rows, the SQL version transfers a few thousand.
The two answers are not identical
Compare the two outputs above. They look similar but differ in two places.
| Situation | SQL `GROUP BY` | pandas `groupby` default |
|---|---|---|
| Rows whose group key is NULL | Form their own group | Dropped, because `dropna=True` |
| `SUM` of a group containing only NULLs | NULL (becomes NaN) | `0.0`, because `min_count=0` |
| `COUNT(total)` versus `count` | Both skip NULLs | Both skip NaN |
| `COUNT(*)` | Counts every row | No direct equivalent. Use `size()` |
| Group order without `ORDER BY` | Unspecified | Sorted by key |
In the example data, SQL returns a NULL-customer group with revenue 45.0, and a Linus group with revenue NaN. The pandas result has no NULL-customer group, and Linus shows 0.0.
To make pandas follow SQL semantics, change two arguments:
matching = (
everything.groupby("customer", dropna=False)
.agg(
revenue=("total", lambda s: s.sum(min_count=1)),
orders=("id", "count"),
)
.reset_index()
)
print(matching)dropna=False keeps the NULL group, and min_count=1 makes a sum of no valid values NaN. The row order still differs, because pandas puts the NaN key last and SQLite sorts NULL first.
Other semantic differences
- Integer division. In SQLite,
SELECT 5 / 2returns2. In pandas,5 / 2returns2.5. Cast one operand, for example5 * 1.0 / 2, when you compute ratios in SQL. - Text comparison. SQLite
=on text is case-sensitive by default. Other databases may be case-insensitive depending on collation. pandas string comparison is always case-sensitive unless you lower-case first. - Dates. SQLite stores dates as text, so a comparison such as
created_at >= '2024-02-01'is a string comparison. It works for ISO 8601 text and gives wrong answers for formats such as02/01/2024. In pandas, afterparse_dates, comparisons are real datetime comparisons. - Floating-point sums. The database and pandas add numbers in different orders, so totals can differ in the last digits. Compare with a tolerance, not
==.
Keep detail rows in pandas when you will reuse them
SQL is not always the right place. Load the rows when any of these is true:
- You will compute several different summaries from the same rows. One load is cheaper than several queries.
- The operation is awkward in SQL, such as time-series resampling, pivoting, rolling windows with custom logic, or applying a Python function.
- The data must be combined with something that is not in the database.
- You are exploring, and you do not yet know which summary you need.
For example, monthly totals are a one-liner on detail rows:
detail = pd.read_sql_query(
"SELECT customer, total, created_at FROM orders",
conn,
parse_dates=["created_at"],
)
monthly = detail.set_index("created_at")["total"].resample("MS").sum()
print(monthly)Even here, you still select only the three columns you need. The id column was not loaded.
Decision criteria
The same decision as a table:
| Question | Lean toward SQL | Lean toward pandas |
|---|---|---|
| How big is the table compared with your memory? | Much bigger | Fits comfortably |
| Is a suitable index available? | Yes | Not relevant |
| Is the output a small summary? | Yes | No, you need the rows |
| Will you reuse the detail rows? | No | Yes |
| Does the logic need Python code? | No | Yes |
| Is the database shared and busy? | Be careful: heavy queries cost others | Pull once, then work locally |
The last row matters in practice. A complex aggregation on a production database can slow down other users. Pulling a filtered extract and working locally is sometimes the more polite choice.
Measure instead of guessing
This example builds 200,000 rows, computes the same per-customer totals both ways, and checks that they agree. Run it to see the transfer cost on your machine. The timings vary between machines.
import random
import sqlite3
import time
import pandas as pd
rng = random.Random(0)
rows = [
(
i,
f"cust{rng.randrange(1000)}",
round(rng.uniform(1, 500), 2),
f"2024-{rng.randrange(1, 13):02d}-{rng.randrange(1, 29):02d}",
)
for i in range(200_000)
]
big = sqlite3.connect(":memory:")
big.execute(
"CREATE TABLE orders (id INTEGER PRIMARY KEY, customer TEXT, total REAL, created_at TEXT)"
)
big.executemany("INSERT INTO orders VALUES (?, ?, ?, ?)", rows)
big.commit()
def timed(label, func):
start = time.perf_counter()
result = func()
print(f"{label}: {time.perf_counter() - start:.3f}s, {len(result)} rows")
return result
def in_pandas():
full = pd.read_sql_query("SELECT * FROM orders", big)
print(f"full frame: {full.memory_usage(deep=True).sum() / 1e6:.1f} MB")
return full.groupby("customer", as_index=False)["total"].sum()
def in_sql():
return pd.read_sql_query(
"SELECT customer, SUM(total) AS total FROM orders GROUP BY customer",
big,
)
pandas_result = timed("pandas groupby", in_pandas)
sql_result = timed("SQL GROUP BY", in_sql)
merged = pandas_result.merge(sql_result, on="customer", suffixes=("_pandas", "_sql"))
same = ((merged["total_pandas"] - merged["total_sql"]).abs() < 1e-6).all()
print("results agree:", same)The SQL version transfers 1,000 rows. The pandas version transfers 200,000 and builds a frame that you can size with memory_usage. With a database on another machine, the gap grows because every row crosses the network.
Common mistakes
- Using
SELECT *out of habit. Name the columns. This also protects your code when someone adds a column to the table. - Filtering in pandas on a column that SQL could filter. This is the most frequent cause of slow loads.
- Aggregating in SQL, then discovering you need detail. Re-querying is fine for small data. For slow queries, load the detail once and aggregate locally.
- Assuming the two engines agree on NULL, case and integer division. Test on a sample.
- Concatenating values into the SQL string to build filters. Use
params. - Relying on row order without
ORDER BY. SQL result order is unspecified unless you ask for one, and a later query plan change can reorder rows. - Pulling a huge result when you need a full scan anyway. Aggregate in SQL if you can. If not, read in pieces, which the next chapter covers with
chunksize.
Exercise
A table events(id, user_id, kind, created_at) has 80 million rows. You need the number of 'click' events per user for March 2024, and you have an index on created_at. Write the read_sql_query call, and explain which parts of the work happen in the database.
Show answer
Use pushdown for both the filter and the aggregation:
pd.readsqlquery(
"SELECT userid, COUNT(*) AS clicks FROM events WHERE kind = ? AND createdat >= ? AND createdat < ? GROUP BY userid",
conn,
params=("click", "2024-03-01", "2024-04-01"),
)
The database applies the kind filter and the date range, which can use the index on created_at because the column is not wrapped in a function. It then groups and counts. Only one row per active user crosses the connection, not 80 million rows.
Exercise
A colleague moves SELECT customer, SUM(total) FROM orders GROUP BY customer into pandas as df.groupby("customer")["total"].sum(). The numbers change for two customers. What are the two likely causes, and what two changes make pandas match SQL?
Show answer
The first cause is rows with a NULL customer. SQL keeps them as their own group, and pandas drops them by default. The second cause is customers whose total values are all NULL. SQL returns NULL for the sum, and pandas returns 0.0. Passing dropna=False to groupby keeps the NULL-key group, and using sum(min_count=1) makes an all-missing group return NaN.