E3-Rewrite: Learning to Rewrite SQL for Executability, Equivalence,and Efficiency

Dongjie Xu, Yue Cui, Weijie Shi, Qingzhi Ma, Hanghui Guo, Jiaming Li, Yao Zhao, Ruiyuan Zhang, Shimin Di, Jia Zhu, Kai Zheng, Jiajie XuarXiv 2025

TL;DR

This paper introduces E³-Rewrite, a novel framework that uses Large Language Models (LLMs) trained with Reinforcement Learning (RL) to automatically rewrite SQL queries for better performance, equivalence, and executability. By incorporating query execution plans as "hints" and using a curriculum-based training approach, E³-Rewrite significantly outperforms existing methods in reducing query execution time and ensuring correctness.

What Problem Does This Paper Address?

Database systems rely heavily on efficient query processing, and SQL query rewriting is a key technique to achieve this. The goal is to transform an SQL query into an equivalent one that runs faster. Traditional methods often use predefined rules, which are rigid and struggle with complex or novel queries. While LLMs show promise in generating rewrites, they often lack "execution awareness," leading to queries that are syntactically incorrect, semantically different from the original, or even slower. This paper tackles the challenge of creating an LLM-based system that can reliably produce SQL rewrites that are not only equivalent to the original but also executable and significantly more efficient, overcoming the limitations of rule-based systems and naive LLM applications.

Methods

E³-Rewrite employs a multi-component approach:

  • Execution Hint Injection: The system first analyzes the input SQL query using EXPLAIN or EXPLAIN ANALYZE to obtain its execution plan. This plan, which details how the database system intends to execute the query (e.g., join orders, scan types, bottlenecks), is linearized and prepended to the original query as a "hint." This provides the LLM with crucial structural and performance information.
  • Two-Stage Reinforcement Learning (RL): Instead of relying on fixed rules, E³-Rewrite uses RL to train an LLM. The core idea is to learn from execution feedback.
  • GRPO Algorithm: The paper utilizes the Group-Relative Policy Optimization (GRPO) algorithm, which is well-suited for handling sparse and delayed rewards common in SQL rewriting.
  • Composite Reward Function: A multi-objective reward function is designed to evaluate rewrites based on:
  • Executability: Does the query parse and run?
  • Equivalence: Does it produce the same results as the original? (Verified using a combination of formal checkers like QEDSOLVER and execution-based comparisons).
  • Efficiency: How much does it reduce execution time compared to the original?
  • Curriculum-Based Training: To manage the complexity of optimizing multiple objectives, training is staged. First, the model focuses on executability and equivalence. Once these are stable, efficiency is introduced as an optimization goal. This prevents conflicting reward signals from destabilizing the learning process.
  • Hybrid Demonstration Retrieval: During inference, the system retrieves similar, successful rewrites from a dynamically updated pool. Similarity is measured using a hybrid metric combining structural (AST edit distance) and semantic (contextual embeddings) similarity. This helps guide the LLM and improve generalization.

Datasets

The paper evaluates E³-Rewrite on three standard SQL rewriting benchmarks:

  • TPC-H: A decision support benchmark with 22 parameterized query templates.
  • IMDB (JOB): Derived from the Join Order Benchmark, focusing on analytical queries with diverse join patterns.
  • DSB: Extends TPC-DS to model modern decision support scenarios with complex queries.

The authors generated approximately 2,000 queries for TPC-H and used existing datasets for IMDB and DSB.

Key Insights and Ideas

  • Execution Plans as LLM Hints: The most significant innovation is treating query execution plans as explicit "hints" for LLMs. This moves beyond just providing the SQL text and allows the LLM to understand why a query is slow, not just what it does.
  • RL for Non-Differentiable Objectives: SQL rewriting involves objectives (executability, equivalence, efficiency) that are not easily differentiable. Using RL with carefully designed rewards is a powerful way to train models for these tasks.
  • Curriculum Learning for Stability: The staged training approach is crucial. Trying to optimize for all three criteria simultaneously from the start is notoriously difficult. By building correctness first, then efficiency, the system achieves more stable and effective learning.
  • Hybrid Retrieval for Generalization: Combining structural and semantic similarity for demonstration retrieval allows the system to leverage past successes more effectively, even for queries with slightly different structures but similar intents.

Key Results

E³-Rewrite demonstrates substantial improvements across all benchmarks:

  • Execution Efficiency: It can shorten query execution time by up to 25.6% relative to leading baselines. For example, on TPC-H, it reduced average latency from 78.81s to 29.67s.
  • Equivalence Preservation: E³-Rewrite produces up to 24.4% more rewrites that meet strict equivalence criteria, achieving equivalence rates as high as 99.6% on TPC-H.
  • Robustness: The system shows strong scalability, maintaining performance across different TPC-H dataset sizes (1GB to 10GB), outperforming baselines that degrade significantly.
  • Ablation Studies: Removing key components like RL, execution hints, or demonstration retrieval led to noticeable drops in performance, highlighting the synergistic contribution of each module.

Limitations and Future Work

  • LLM Dependence: The performance is still tied to the capabilities of the underlying LLM. While E³-Rewrite improves upon direct LLM application, the quality of the generated rewrites is influenced by the LLM's inherent strengths and weaknesses.
  • Computational Cost: While the rewrites are more efficient, the training process and the inference-time evaluation (especially equivalence checks) can be computationally intensive.
  • Future Work: The authors suggest exploring more advanced RL techniques, further improving the demonstration retrieval mechanism, and extending the framework to handle more complex SQL features or different database systems. The paper also hints at the potential for E³-Rewrite to be integrated into existing database optimizers.

Summary updated

BibTeX
@misc{xu2025e,
  author = {Dongjie Xu and Yue Cui and Weijie Shi and Qingzhi Ma and Hanghui Guo and Jiaming Li and Yao Zhao and Ruiyuan Zhang and Shimin Di and Jia Zhu and Kai Zheng and Jiajie Xu},
  title = {{E3-Rewrite: Learning to Rewrite SQL for Executability, Equivalence,and Efficiency}},
  year = {2025},
  eprint = {2508.09023},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2508.09023},
}
Figure