03. How Query Plan Caching Works

 

How Query Plan Caching Works


When a SQL query is executed:

First Time Execution:

  • The database parses and optimizes the query.
  • It saves the execution plan in memory (query cache).

Next Time (Same Query):

  • If the exact same query (including whitespace and case) is executed again,
  • The database reuses the saved plan.
  • This saves CPU usage and makes the query faster

 

MySQL:

  • MySQL does not cache execution plans for regular SQL queries (unlike Oracle or SQL Server).
  • It only caches plans for Prepared Statements and Stored Procedures.

MongoDB:

  • MongoDB is handle a cache for the all the queries (regular queries, But not it happen in MySQL).

 

What happens when the  underlying database structure (like indexes) changes after a query plan has been cached

When a database index changes (created, dropped, or modified), the cached execution plan might become invalid, suboptimal, or even fail. So the database needs to detect the change and take action.

1. MySQL:

MySQL automatically invalidates cached plans for affected tables. On next execution, the plan will be recompiled with the new index metadata.

MySQL checks a "version" or metadata change of the table/index to determine plan invalidation.

2. MongoDB

Do a trial run again on the next query execution. Cache the new best plan based on the updated index situation.

MongoDB also evicts stale plans over time via LRU (Least Recently Used).

 

DBMS

Plan Selection Method

Plan Caching (Raw Queries)

Reuse with Prepared Statements

Notes

Oracle

Cost-Based Optimization (CBO)

Yes (Library Cache)

Yes

Very advanced optimizer; uses Adaptive Plans

MS SQL Server

Cost-Based Optimization

Yes (Plan Cache)

Yes

Includes parameter sniffing, plan freezing

PostgreSQL

Cost-Based (no plan cache for raw SQL)

No (re-optimizes each raw SQL)

Yes

Optimizes each query unless using prepared

MySQL

Cost-Based

No (unless using prepared stmt)

Yes

Plan cache deprecated in 8.x for raw SQL

MongoDB

Trial Execution (real data)

Yes (Plan Cache after 1st run)

N/A (no prepared stmt needed)

Plan cache auto-managed

 

Comments

Popular posts from this blog

Database - Topics

02. Spring – Creating spring project clone it with GIT step by step.

01. Steps in SQL Query Execution (MySQL)