On this page
SQL Query Execution Lifecycle
Prev: Aggregations, CTEs & Window Functions | Up: sql | Next: design_patterns
Rel: Indexing & Storage Engines, PostgreSQL Indexes & EXPLAIN ANALYZE, Python sqlite3 Patterns
Ref: SQLite — EXPLAIN QUERY PLAN | PostgreSQL — Using EXPLAIN
Tags: #public #databases #sql #internals #query-planner
Contents
- > Logical Evaluation Order (Why Aliases Fail in `WHERE`)
- > Physical Execution Pipeline (Parser to Disk/WAL)
- > Join Execution Strategies
- > Runnable `EXPLAIN QUERY PLAN` Tracer (Python `sqlite3`)
Logical Evaluation Order (Why Aliases Fail in WHERE)
Although you write SELECT first, SQL evaluates clauses in a strict logical order:
1. FROM / JOIN -> Assemble base tables and join rows (applying ON predicates)
2. WHERE -> Filter individual rows (cannot reference SELECT aliases or aggregates)
3. GROUP BY -> Partition remaining rows into groups
4. HAVING -> Filter groups using aggregate predicates
5. SELECT -> Evaluate expressions, window functions, and assign column aliases
6. DISTINCT -> Deduplicate projected rows
7. ORDER BY -> Sort result set (can reference SELECT aliases)
8. LIMIT / OFFSET -> Truncate final output rows
This explains why SELECT price * qty AS total FROM items WHERE total > 100 fails — WHERE runs at step 2, before total exists at step 5.
Physical Execution Pipeline (Parser to Disk/WAL)
Under the hood, the database engine transforms SQL text into physical I/O operations:
SQL Text
├── 1. Lexer & Parser -> Abstract Syntax Tree (AST)
├── 2. Analyzer / Binder -> Resolve table/column names, check types & permissions
├── 3. Rewriter -> Expand views, fold constants, flatten subqueries
├── 4. Cost-Based Planner -> Use table statistics (ANALYZE) to pick scan & join plan
├── 5. Executor -> Pull tuples through iterator tree (Scan -> Filter -> Join -> Sort)
└── 6. Storage Engine -> Read/write pages via Buffer Pool; log mutations to WAL
Join Execution Strategies
- Nested Loop Join: Best when the outer input is small and the inner table has an index on the join key.
- Hash Join: Builds an in-memory hash table on the smaller input; fast for large equi-joins without sorted indexes (PostgreSQL).
- Merge Join: Zips two pre-sorted inputs (from B-Tree indexes or sorts) in linear time.
Runnable EXPLAIN QUERY PLAN Tracer (Python sqlite3)
This stdlib-only script demonstrates how adding a covering composite index turns a full SCAN + USE TEMP B-TREE FOR ORDER BY into a single SEARCH ... USING COVERING INDEX:
import sqlite3
con = sqlite3.connect(":memory:")
con.executescript("""
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
user_id INTEGER NOT NULL,
status TEXT NOT NULL,
total_cents INTEGER NOT NULL
);
""")
con.executemany(
"INSERT INTO orders (user_id, status, total_cents) VALUES (?, ?, ?)",
[(i % 20, "paid" if i % 3 else "pending", i * 100) for i in range(1, 500)],
)
query = """
SELECT total_cents
FROM orders
WHERE user_id = 7 AND status = 'paid'
ORDER BY total_cents DESC
"""
print("Before index:")
for row in con.execute(f"EXPLAIN QUERY PLAN {query}"):
print(" ", row)
con.execute("CREATE INDEX idx_orders_user_status_total ON orders (user_id, status, total_cents)")
print("After covering composite index:")
for row in con.execute(f"EXPLAIN QUERY PLAN {query}"):
print(" ", row)
Linked from
- tuts/databases/design_patterns/indexing_and_storage_engines
- tuts/databases/postgresql/indexes_and_explain_analyze
- tuts/databases/sql
- tuts/databases/sql/aggregations_ctes_and_windows
- tuts/databases/sql/clauses
- tuts/databases/sql/clauses/CREATE_INDEX
- tuts/databases/sql/clauses/CREATE_TABLE
- tuts/databases/sql/clauses/DELETE
- tuts/databases/sql/clauses/EXPLAIN
- tuts/databases/sql/clauses/FROM
- tuts/databases/sql/clauses/GROUP_BY
- tuts/databases/sql/clauses/HAVING
- tuts/databases/sql/clauses/INSERT
- tuts/databases/sql/clauses/JOIN
- tuts/databases/sql/clauses/LEFT_JOIN
- tuts/databases/sql/clauses/LIMIT
- tuts/databases/sql/clauses/ON_CONFLICT
- tuts/databases/sql/clauses/ORDER_BY
- tuts/databases/sql/clauses/RETURNING
- tuts/databases/sql/clauses/SELECT
- tuts/databases/sql/clauses/UPDATE
- tuts/databases/sql/clauses/WHERE
- tuts/databases/sql/clauses/WITH
- tuts/databases/sql/dml_and_querying
- tuts/databases/sql/joins_and_set_operations
- tuts/databases/sql/query_execution_lifecycle
Related notes
- tuts/databases/sql Linked here; links to this page; shared tags: #databases, #sql
- tuts/databases/sql/aggregations_ctes_and_windows Linked here; links to this page; shared tags: #databases, #sql
- tuts/databases/design_patterns/indexing_and_storage_engines Linked here; links to this page; shared tags: #databases
- tuts/databases/postgresql/indexes_and_explain_analyze Linked here; links to this page; shared tags: #databases
- tuts/databases/sql/clauses links to this page; shared tags: #databases, #sql
- tuts/databases/sql/clauses/CREATE_INDEX links to this page; shared tags: #databases, #sql
- tuts/databases/sql/clauses/CREATE_TABLE links to this page; shared tags: #databases, #sql
- tuts/databases/sql/clauses/DELETE links to this page; shared tags: #databases, #sql
- tuts/databases/sql/clauses/EXPLAIN links to this page; shared tags: #databases, #sql
- tuts/databases/sql/clauses/FROM links to this page; shared tags: #databases, #sql