AI suggestion panel overlaid on SQL editor showing rewritten query

How AI Query Rewriting Actually Works

AI query rewriting sounds like magic but it's built on well-understood components. The magic is in putting them together at production scale with low latency. Here's what actually happens when Dreambase rewrites a query.

Step 1: Parse and normalize

The query arrives as a string. Before any analysis can happen, it needs to be parsed into an AST (abstract syntax tree) and normalized: literals replaced with parameters, whitespace and case standardized, aliases resolved. Normalization is what allows the system to recognize that two queries that look different are semantically identical, and to reuse analysis results across them.

Step 2: Fetch the execution plan

The normalized query is sent to the database as EXPLAIN (ANALYZE false, FORMAT JSON) — a dry run that returns the query plan without executing it. The plan contains cost estimates, node types (sequential scan, index scan, nested loop, hash join, etc.), estimated row counts, and the specific indexes the planner intends to use.

Step 3: Pattern matching against known rewrite rules

A rule engine compares the plan structure against a library of known inefficient patterns: nested loops on large estimated row counts, sequential scans on columns that have an index, correlated subqueries that can be converted to joins, N+1 patterns in ORMs. Most rewrites come from this deterministic rule layer, not the model.

Step 4: Model-assisted optimization for novel patterns

For plans that don't match known patterns but still show high cost estimates, a model trained on millions of query plan examples suggests alternative formulations. The model doesn't write SQL from scratch — it recommends structural transformations: “convert this correlated subquery to a lateral join,” “add this covering index to eliminate a sort node,” “push this filter above this join to reduce cardinality earlier.”

Step 5: Validate and serve

Every candidate rewrite is validated against the original for result equivalence before it's served to the application. This validation step is non-negotiable: a rewrite that changes results isn't optimization, it's a bug.