On this page
  1. SQL Query Execution Lifecycle
  2. Contents
  3. Logical Evaluation Order (Why Aliases Fail in WHERE)
  4. Physical Execution Pipeline (Parser to Disk/WAL)
  5. Join Execution Strategies
  6. Runnable EXPLAIN QUERY PLAN Tracer (Python sqlite3)

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)

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


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

Related notes