Introduction
When a database receives a query, it can find many ways to get the answer. Choosing the fastest and cheapest way is a big challenge. Cost-based optimization helps pick the best plan by estimating the work needed for each option.
Imagine you want to travel from home to a new restaurant. You can choose different routes: a highway, side streets, or a scenic path. You check a map app that estimates time and traffic for each route and suggests the fastest one. Sometimes, if traffic changes, the app updates your route while you drive.
┌─────────────────────────────┐
│ User Query Input │
└─────────────┬───────────────┘
│
▼
┌─────────────────────────────┐
│ Generate Execution Plans │
└─────────────┬───────────────┘
│
▼
┌─────────────────────────────┐
│ Estimate Cost for Each │
│ Execution Plan │
└─────────────┬───────────────┘
│
▼
┌─────────────────────────────┐
│ Select Plan with Lowest │
│ Estimated Cost │
└─────────────┬───────────────┘
│
▼
┌─────────────────────────────┐
│ Execute Query Plan │
└─────────────────────────────┘import sqlite3 conn = sqlite3.connect(':memory:') cur = conn.cursor() cur.execute('CREATE TABLE employees (id INTEGER, name TEXT, dept TEXT)') cur.executemany('INSERT INTO employees VALUES (?, ?, ?)', [ (1, 'Alice', 'Sales'), (2, 'Bob', 'HR'), (3, 'Charlie', 'Sales'), (4, 'Diana', 'IT') ]) # Run EXPLAIN QUERY PLAN to see the optimizer's plan cur.execute('EXPLAIN QUERY PLAN SELECT * FROM employees WHERE dept = "Sales"') for row in cur.fetchall(): print(row)