Diff-SQL:基于补丁生成与约束对齐的SQL效率优化
Diff-SQL: SQL Efficiency Optimization via Patch Generation and Constraint Alignment
- The Chinese University of Hong Kong, Shenzhen(香港中文大学(深圳))
- The University of Hong Kong(香港大学)
- National University of Singapore(新加坡国立大学)
机构由 AI 辅助整理,请以论文原文为准。
AI总结:
Diff-SQL提出两阶段框架,通过补丁生成与约束对齐解耦SQL优化,缓解目标错位,在提升效率的同时减少准确率下降,并在小模型上显著提升R-VES。
AI中文摘要:
SQL效率优化旨在将慢查询转换为语义等价但执行更快的替代方案。然而,以端到端方式直接使用大型语言模型优化SQL常常引发目标错位(Objective Misalignment),这在优化与正确性之间造成根本性矛盾,使得直接的全量SQL重写对于面向执行的数据库应用而言不可靠。为解决此问题,我们提出Diff-SQL,一个两阶段框架,将面向效率的优化与约束感知的对齐解耦。第一阶段识别优化机会并以统一差异补丁(unified diff patch)的形式提出针对性编辑,第二阶段通过基于策略的强化学习进行训练,在可执行性和语义等价约束下修正输出。为训练和评估Diff-SQL,我们构建了一个自动化流水线,从StackOverflow挖掘优化知识,并通过级联过滤构建慢-快SQL对。我们进一步引入Effi-SQL基准,包含1,100个经人工验证的跨五种SQL方言的慢-快对。实验表明,目标错位在现有基于LLM的SQL优化方法中普遍存在,直接的全量SQL优化在Claude-Opus-4.6等前沿模型上平均导致22.7%的执行准确率下降,最差模型下降43.0%。Diff-SQL缓解了这一权衡。作为仅推理策略,它在三个强基座模型上平均提升R-VES 10.0%,同时平均减少执行准确率下降6.11%。通过执行接地训练,Diff-SQL进一步使7B模型将R-VES从33.42%提升至46.83%,表明所提出的两阶段优化与对齐范式能够在本地小模型部署场景中同时实现更强的效率和更好的正确性。
英文摘要:
SQL efficiency optimization aims to transform slow queries into semantically equivalent but faster alternatives. However, directly optimizing SQL with large language models in an end-to-end fashion often induces Objective Misalignment which creates a fundamental tension between optimization and correctness, making direct full SQL rewriting unreliable for execution-facing database applications. To address this problem, we propose Diff-SQL, a two-stage framework that decouples efficiency-oriented optimization from constraint-aware alignment. The first stage identifies optimization opportunities and proposes targeted edits in the form of a unified diff patch, while the second stage is trained with on-policy reinforcement learning to revise outputs under executability and semantic-equivalence constraints. To train and evaluate Diff-SQL, we construct an automated pipeline that mines optimization knowledge from StackOverflow and builds Slow-Fast SQL pairs through cascaded filtering. We further introduce Effi-SQL, a benchmark containing 1,100 human-verified Slow-Fast pairs across five SQL dialects. Experiments show that Objective Misalignment is widespread across existing LLM-based SQL optimization methods, where direct full SQL optimization causes an average 22.7% execution accuracy degradation across frontier models such as Claude-Opus-4.6, with the worst model dropping by 43.0%. Diff-SQL alleviates this trade-off. As an inference-only strategy, it improves R-VES by 10.0% on average while reducing execution accuracy degradation by 6.11% on average across three strong base models. With execution-grounded training, Diff-SQL further enables a 7B model to improve R-VES from 33.42% to 46.83%, demonstrating that the proposed two-stage optimization-and-alignment paradigm can deliver both stronger efficiency and better correctness in local, small model deployment settings.