The same SQL query is faster the second time. What did pandas, SQLAlchemy or Oracle cache?

June 26, 2025

I was looking for a Python library that could reuse database connections for a report. Then I remembered some advice: “what about pandas someone tell me we can increase pandas's cache size to improve performance on sql query why is that”. Reusing something can certainly make the second visit faster. But did we reuse the connection, the instructions for computing the report, or the answer itself?

If Python sends the SQL to Oracle again, Oracle can reuse a parsed cursor and its execution plan, avoid disk reads by keeping data blocks in memory, or, on a valid SQL result-cache hit, return the answer it computed earlier. Those save three different steps. Before tuning any of them, find out whether a second query even reached the database.123

SQLAlchemy reused my connection and logged “cached”. Did it send the SQL again?

Suppose the report is a single number: SELECT SUM(n) FROM report. Before the first query, the program has to open a connection and authenticate. SQLAlchemy is a Python database toolkit. It can execute SQL directly, or its object-relational mapper (ORM) can represent database rows as Python objects. Both can use a connection pool. Return a connection to the pool after use, and the next request may borrow that already-authenticated connection. Two calls that query the total still issue two SELECTs. If someone inserts a row in between, the second query can see a different total.4

There is also a SQL compilation cache. Take text("SELECT SUM(n) FROM report WHERE n >= :minimum"). Here :minimum is a bind parameter: its value is supplied at execution time. The first time through, SQLAlchemy prepares a statement in a form the driver can execute. Change only the threshold, and SQLAlchemy can reuse that compiled form. Its log entry [cached since …] refers to this step. The driver still receives the new value and the database still executes the query. Increasing the engine's query_cache_size can help if useful compiled statements are being evicted and recompilation costs a measurable amount.5

The ORM has a narrower shortcut. Within the same session, Session.get(Report, 42) can return an existing, unexpired object for primary key 42 from the session's identity map. Filtering reports by date or requesting a sum normally still sends SQL.6

Will pandas reuse yesterday's DataFrame if the SQL text matches?

Each call to pd.read_sql_query(sql, conn) executes a query. There is no automatic SQL-result cache here and no capacity setting for one. A DataFrame is the in-memory table returned by the call. Keep it in df and you can reread the data already fetched as often as you like.7

I tried both operations with a SQLite table containing just 10. I saved the sum as df, inserted 5, then reread df: still 10. Calling read_sql_query again returned 15. The database had received two SELECTs. Does pandas use SQLAlchemy underneath? In this example I passed it a SQLAlchemy connection. In pandas 2.2.3 an ordinary SQL string goes through exec_driver_sql, bypassing SQLAlchemy's statement compilation cache. A SQLAlchemy text(...) object goes through the compilation path. I tried thresholds of 0 and 8 with the same statement structure: the second compilation was a cache hit, but the two sums were 15 and 10.75

Why would a backend use SQLAlchemy directly? If the endpoint returns one total, conn.scalar(...) delivers precisely one value. pandas can issue the same query over the same connection, then builds a table that the endpoint has to unpack. That extra work is worth doing when the application actually needs tabular operations, such as comparing reports by month and department. MLflow 2.22.0 illustrates both cases: it uses SQLAlchemy transactions to save a run and its tags together, and returns a pandas DataFrame by default when users call search_runs() to compare metrics across runs.8

What can I tune in pandas if fetching or processing the rows is slow?

SymptomChange to tryWhat to measure
The page shows one number but loads every row and sums in PythonFilter with WHERE and aggregate with SUM in SQL. If the page needs detail, select only the columns it displays.Rows and columns returned, and elapsed time to fetch the entire result.
I need every row, but a single DataFrame is too largeTry chunksize=1000, process a chunk and release it before reading more. The driver may buffer rows separately.Peak memory for the whole process. When timing, consume all chunks. Chunk size offers little for the one-row sum.7
Fetching is done, but date parsing is slow or a column uses too much memoryGive parse_dates={"report_date": "%Y-%m-%d"} an explicit format, or use dtype to choose a type appropriate to the data range.Conversion time on the same rows and total bytes from df.memory_usage(deep=True).sum().79

pandas does use the word cache for other operations. For example, pd.to_datetime(..., cache=True) may reuse parsed dates within one conversion in 2.2.3. An input with at most 50 values skips this cache. For larger inputs it samples for repeated values before deciding whether caching is worthwhile. That saves parsing the same date string over and over. The original tuning suggestion never named a function or setting, so I can't identify which operation it referred to.10

Count the SELECTs before timing anything

Here is a test using SQLAlchemy 2.x and an in-memory SQLite database. Give the pool just one connection, then count three things independently: physical connections opened, connections borrowed, and SELECT statements sent. Finally, wrap the query function in Python's own result cache.11

Two calls for the same reportNew physical connectionsAdditional SELECTsTotals displayed
Query directly both times, using the connection already opened to create the table0210, 10
Cache the first answer in Python and reuse it on the second call0110, 10

Now insert 5. A direct query returns 15, but the Python cache still returns 10 until I clear it. For a historical snapshot, 10 may be exactly what I want. If the page promises the current total, the app needs an invalidation rule. If different users can select different departments, dates or access scopes, those inputs also belong in the cache key.

Does increasing this cache help? lru_cache(maxsize=1) keeps one answer, identified by the arguments. In the script there is only one possible key, so raising the limit to 100 saves no queries. Suppose instead that reports A and B use different keys and users open A, B, A, B with unchanged data. From an empty cache with capacity one, each new key evicts the other and all four requests query the database. With capacity two, only the first two query it. Check cache_info() alongside the SELECT count to see which pattern you actually have.12

The script uses connect for physical connections, checkout for borrowing and before_cursor_execute for SQL sent to the driver. No separate database service is required.

from collections import Counter
from functools import lru_cache

from sqlalchemy import create_engine, event, text
from sqlalchemy.pool import QueuePool

engine = create_engine("sqlite://", poolclass=QueuePool, pool_size=1, max_overflow=0)
counts = Counter()

@event.listens_for(engine, "connect")
def connected(connection, record):
    counts["connect"] += 1

@event.listens_for(engine, "checkout")
def borrowed(connection, record, proxy):
    counts["checkout"] += 1

@event.listens_for(engine, "before_cursor_execute")
def executing(conn, cursor, statement, parameters, context, executemany):
    if statement.startswith("SELECT"):
        counts["select"] += 1

with engine.begin() as conn:
    conn.exec_driver_sql("CREATE TABLE report (n INTEGER)")
    conn.exec_driver_sql("INSERT INTO report VALUES (10)")

def read_total():
    with engine.connect() as conn:
        return conn.scalar(text("SELECT SUM(n) FROM report"))

print("initial", dict(counts))
print("uncached reads", read_total(), read_total(), dict(counts))
cached_total = lru_cache(maxsize=1)(read_total)
print("cached reads", cached_total(), cached_total(), dict(counts))
with engine.begin() as conn:
    conn.exec_driver_sql("INSERT INTO report VALUES (5)")
print("after insert", cached_total(), read_total())
cached_total.cache_clear()
print("after clearing cache", cached_total())
engine.dispose()

Creating the table borrows the connection once. After the two uncached calls, cumulative checkouts reach three and SELECTs reach two. After the two cached calls, checkouts reach four and SELECTs reach three. The entire script uses a single physical connection.

“maybe we can increase database's cache size? does oracle has cache for queries”

Assume we've established that the second SELECT reached Oracle. Follow the work the database does to compute SUM(n), and ask which part survived from the first execution.

What Oracle retainedWhat the next request can saveWork that remains
A parsed cursor, including the execution plan describing how to fetch the rowsReuse the parsed form and plan when the SQL and execution environment satisfy cursor-sharing conditionsExecute the plan and calculate the current total.1
Data blocks, the units of storage holding rows, in the database buffer cacheAvoid reading a needed block from disk when it is still in memoryVisit the blocks, apply filters and add the numbers.2
A valid sum in the server's SQL result cacheReturn the saved total for an eligible query on a cache hitReceive the request and send back the result.3

Even when every number comes from memory, Oracle may have to add them up again. A faster second run alone cannot distinguish a warm scan from reuse of the final answer.

What would count as evidence on Oracle?

Keep the SQL, bind values, rows returned and fetch behavior constant. On the client, time connection checkout, execution to the first readable batch, and fetching the rest and constructing the DataFrame. Driver prefetch can make the last two stages overlap. On the server, Oracle can retain several executable child cursors for the same SQL. In a controlled workload, compare before-and-after counters for the same child cursor.13

  • Did EXECUTIONS increase? If the client served an old DataFrame or an application cache entry, Oracle may have seen no query.
  • How did BUFFER_GETS (logical reads) and DISK_READS (physical reads) change? Fewer physical reads with substantial logical reads is consistent with warm blocks that still had to be scanned.
  • Oracle's qualification matters: “Enabling the result cache does not guarantee that a specific result set will be included in the server or client result cache.” Check instance settings, query eligibility, the RESULT CACHE operation in the execution plan, and result-cache statistics for that run. The plan locates the operation. The counters help determine whether it actually hit.3

If you have permission to read Oracle's dynamic performance views, take snapshots of these columns before and after on the same instance, using the report's SQL ID. The counters are cumulative. Other sessions executing the same child cursor also contribute.13

SELECT child_number, plan_hash_value, executions, buffer_gets, disk_reads, rows_processed
FROM v$sql
WHERE sql_id = :report_sql_id
ORDER BY child_number;

Would giving Oracle more memory actually help?

If the first run has many physical reads and the second has almost none, those blocks already stayed in memory between the two runs. A larger buffer might help under a different pattern: during a representative peak workload, frequently reused blocks keep getting evicted, and fetching them from disk accounts for substantial wait time. An occasional one-time scan has little opportunity for that kind of reuse.2

In Oracle 19c, V$DB_CACHE_ADVICE estimates physical reads at candidate sizes for the data block buffer cache. With advice enabled and representative activity captured, compare the same buffer pool and block size at SIZE_FACTOR = 1 and at a larger size using ESTD_PHYSICAL_READS. If 25% more space is predicted to save very few reads, it makes a weak case for diverting that memory. A large predicted reduction is a reason for a controlled test against measured I/O waits. The figures are estimates and apply specifically to the buffer cache.14

For the result cache, ask why the answer disappeared. If a valid, popular result is repeatedly evicted for lack of room, capacity could help. If the underlying table changes before every reuse, the old result is invalidated regardless of how much room it has.3

My own batch SQL tool had another form of reuse. Its June 18 JavaScript version saved query state and results so formulas could be recalculated using previously fetched values. That was an application-level snapshot, useful for reproducing an earlier report. Getting today's number calls for a fresh read and a timestamp. I have a project record for the snapshot and no before-and-after Oracle tuning measurement.15

Footnotes

  1. Oracle. (n.d.). Improving real-world performance through cursor sharing. Oracle Database 19c SQL Tuning Guide. Cursor sharing. ↩ ↩2

  2. Oracle. (n.d.). Tuning the database buffer cache. Oracle Database 19c Performance Tuning Guide. Buffer cache and I/O. ↩ ↩2 ↩3

  3. Oracle. (n.d.). Tuning the result cache. Oracle Database 19c Performance Tuning Guide. Quotation from the opening paragraph on eligibility. Original passage and result-cache monitoring. ↩ ↩2 ↩3 ↩4

  4. SQLAlchemy authors. (n.d.). Connection pooling. SQLAlchemy 2.0 Documentation. Pool basics. ↩

  5. SQLAlchemy authors. (2025). Working with engines and connections, SQLAlchemy 2.0.41. GitHub. SQL compilation cache, size and log messages. ↩ ↩2

  6. SQLAlchemy authors. (2025). Session basics, SQLAlchemy 2.0.41. GitHub. Primary-key lookup and ordinary queries. ↩

  7. pandas developers. (2024). SQL I/O, pandas 2.2.3. GitHub. read_sql_query parameters and return value · SQLDatabase.execute on strings and SQLAlchemy statements. ↩ ↩2 ↩3 ↩4

  8. MLflow contributors. (2025). MLflow, v2.22.0. GitHub. create_run and run tags · Session commit and rollback · search_runs output format. ↩

  9. pandas developers. (2024). DataFrame.memory_usage, pandas 2.2.3. GitHub. Memory accounting and the deep option. ↩

  10. pandas developers. (2024). Datetime conversion tools, pandas 2.2.3. GitHub. should_cache and per-conversion reuse. ↩

  11. SQLAlchemy authors. (n.d.). Core events. SQLAlchemy 2.0 Documentation. PoolEvents.checkout · before_cursor_execute. ↩

  12. Python Software Foundation. (n.d.). functools — Higher-order functions and operations on callable objects. Python 3.12 Documentation. Cache size, statistics and clearing. ↩

  13. Oracle. (n.d.). V$SQL. Oracle Database 19c Reference. Per-child-cursor statistics. ↩ ↩2

  14. Oracle. (n.d.). V$DB_CACHE_ADVICE. Oracle Database 19c Reference. Estimated reads and candidate cache sizes. ↩

  15. CaiBorui. (2025, June 18). Add snapshot saving between query completion [local Git commit d5fb229]. level5sql, calcProc.js, functions saveQueriesState, readResults and calculateFormulaResults. ↩

© 2025 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2025-06-26). The same SQL query is faster the second time. What did pandas, SQLAlchemy or Oracle cache?. https://caiborui.com/blog/2025-06-26-en-pandas-sqlalchemy-oracle-query-cache

@misc{borui2025-46998ff1,
  author = {borui},
  title = {{The same SQL query is faster the second time. What did pandas, SQLAlchemy or Oracle cache?}},
  year = {2025},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2025-06-26-en-pandas-sqlalchemy-oracle-query-cache}
}