Manuscript Offprint
arXiv:2610.33946Schema-Free Text-to-SQL: Learning Enterprise Database Structure from Query Logs
Open access. PaperVantage converted this article to text, so layout and figures may differ from the original.
Abstract
Text-to-SQL systems achieve remarkable accuracy on academic benchmarks, yet performance drops dramatically in enterprise deployments. This gap stems from a fundamental assumption: existing approaches require complete schema documentation, but enterprise databases typically lack comprehensive documentation, featuring cryptic naming and implicit relationships. We present the first text-to-SQL framework that operates without schema documentation, instead learning database structure from historical query logs. Query logs encode implicit structural knowledge: which tables are queried together, how they join, and what columns map to business concepts. We construct a knowledge graph from parsed query patterns and introduce entity-driven GraphRAG retrieval that grounds user questions in domain terminology rather than relying solely on embedding similarity. Validated on both an industrial deployment with expert evaluation and the Beaver benchmark, our approach substantially outperforms similarity-based retrieval methods, the dominant industry approach, in both executability and answer quality. On Beaver, we achieve 95.7% execution validity compared to 60.8% for embedding-based retrieval, with expert data engineers preferring our system 70% to 10% on internal deployment. Our work demonstrates that text-to-SQL can operate effectively in schema-ambiguous enterprise environments, enabling natural language database interfaces “in the wild.”
1 Introduction
Text-to-SQL systems have achieved remarkable performance on academic benchmarks, with state-of-the-art methods (Shkapenyuk et al., 2025; Lee et al., 2024; Gao et al., 2023) achieving high accuracy on datasets like Spider (Yu et al., 2018) and BIRD (Li et al., 2023b). Yet these same sys-

Figure 1: State-of-the-art text-to-SQL systems require complete schema documentation unavailable in enterprise settings. Operating with only historical query logs, our approach achieves 95.7% execution validity and 70% expert preference over embedding-based retrieval.
tems struggle dramatically when deployed in enterprise environments (Lei et al., 2025; Chen et al., 2026). This performance gap reflects a fundamental assumption mismatch: current text-to-SQL approaches universally require database identity known upfront, complete table schemas as input, explicit foreign key relationships, and interpretable column names. Enterprise databases offer none of these.
In practice, enterprise data ecosystems present what we term the schema ambiguity problem. Tables and columns lack meaningful descriptions, with names employing domain-specific abbreviations that obscure their meaning to anyone outside the immediate team. Foreign keys are rarely declared explicitly; join relationships exist only in the institutional knowledge of database administrators or embedded in historical query patterns. These environments span hundreds to thousands of tables (Lei et al., 2025; Chen et al., 2026), and schemas evolve continuously as business needs change, rendering any static documentation quickly outdated. These challenges are not edge cases but the norm in enterprise settings, and recent work on enterprise-oriented benchmarks has begun to quantify this gap (Lei et al., 2025; Chen et al., 2025).
Work done during an internship at Amazon.
Our Insight. We observe that while explicit documentation may be absent, enterprise databases contain an underutilized source of structural knowledge: historical query logs. Production SQL queries encode implicit information about database structure, revealing which tables are frequently queried together, how tables join in practice, and what columns map to specific business concepts. Query logs capture what documentation should contain, learned from usage patterns rather than manual annotation.
Based on this insight, we present a text-to-SQL framework that operates without schema documentation, instead constructing a knowledge graph directly from query log analysis. State-of-the-art text-to-SQL systems are not designed for this setting, as they assume complete, human-readable schemas are available as input. Since state-of-the-art text-to-SQL systems are not designed for this setting, practitioners often turn to retrieval-augmented generation (RAG), which uses embedding-based similarity to narrow candidate tables and columns (Zhang et al., 2023). However, embedding similarity fundamentally struggles in enterprise settings: users ask about "approved time-off requests" and "hours worked" while schemas contain identifiers like f_pto_agg and d_att_dtl. This vocabulary mismatch cannot be bridged by semantic similarity alone (Chen et al., 2026). To address this, we introduce entity-driven GraphRAG retrieval: we extract domain entities from user questions and traverse the knowledge graph to identify relevant tables, leveraging historical join patterns to ensure structural coherence.
Enterprise text-to-SQL also demands rethinking evaluation methodology. Open-ended analytical questions frequently admit multiple valid SQL formulations, rendering traditional exact-match metrics inadequate (Lei et al., 2025; Chen et al., 2026). A query asking for “sales trends” might be correctly answered by grouping on weeks or months, selecting different but equally valid column subsets, or joining through alternative paths. We address this through multi-faceted evaluation combining execution-based accuracy (Lei et al., 2025), blind pairwise comparison via LLM-as-judge validated by 83% agreement with expert data engineers, and rubric-based analysis that decomposes SQL quality into interpretable dimensions. Our generated-versus-gold analysis (§6.4) further demonstrates that on open-ended questions, system-generated SQL achieves quality scores matching or exceeding human-written gold standards.
We make the following contributions:
-
The first text-to-SQL framework that operates without schema documentation, learning database structure from historical query logs.
-
Entity-driven GraphRAG retrieval that bridges the vocabulary gap between business terminology and cryptic schema identifiers through domain entity matching.
-
A multi-faceted evaluation framework addressing open-ended question ambiguity through execution-based metrics, expert-validated LLM judging, and rubric-based analysis.
-
Validation on an industrial deployment (240 tables, 70% expert preference) and Beaver benchmark (95.7% vs. 60.8% execution validity), with ablations confirming entity matching as the key contributor.
Our work demonstrates that text-to-SQL can operate effectively in schema-ambiguous enterprise environments, providing a new paradigm for natural language database interfaces “in the wild.”
Retrieval-augmented approaches address schema scale through embedding similarity (Zhang et al., 2023; Eben et al., 2025), but treat schema elements independently without capturing structural relationships. Graph-based methods model structure through relational encodings (Wang et al., 2021; Cao et al., 2021), and Graph RAG (Edge et al., 2025) organizes knowledge into structured graphs, though none leverage query logs. Our approach builds on database workload analysis (Chaudhuri and Narasayya, 1997), adapting log mining to extract semantic rather than physical structure.
3 Task Formulation
Traditional text-to-SQL assumes access to a complete database schema consisting of tables T, columns C, and foreign key relationships FK. Given a natural language question Q and schema S, the task is to generate a SQL query Y that answers the question:
This formulation presupposes that S is fully documented and provided as input. Our setting differs: we have no schema documentation, only a corpus of historical query logs L.
We decompose the problem into three stages. First, we construct a knowledge graph G from the query logs L (offline, before any questions arrive). The graph encodes table metadata, domain entities associated with each table, and join relationships weighted by their frequency in historical queries. Second, given a question Q, we retrieve relevant context from G containing the tables, relationships, and metadata needed to answer the question. Third, we generate the SQL query:
This formulation subsumes the traditional setting: a documented schema S is a degenerate case where structure is provided explicitly rather than inferred from usage patterns. The reverse does not hold. Query logs capture which tables are joined in practice, which columns co-occur, and how domain terminology maps to schema elements. This implicit knowledge cannot be recovered from schema documentation alone.
4 Method
We instantiate the three-stage framework introduced in Task Formulation: knowledge graph construction, entity-driven retrieval, and SQL generation. Figure 2 illustrates the complete pipeline.
4.1 Knowledge Graph Construction
Given a corpus of historical query logs , we construct a knowledge graph through three steps: structural extraction, metadata generation, and entity annotation.
Structural Extraction. We parse each query to identify table references and compute usage frequency:
where is the indicator function. We prioritize tables exceeding a frequency threshold, as these represent core entities in the database ecosystem.
Extracting join relationships from enterprise SQL requires more than syntactic parsing. Queries often contain implicit joins in WHERE clauses, relationships mediated through CTEs, and complex multi-way joins. We prompt an LLM to analyze each query and extract relationship triplets (Appendix B.2):
where , are join columns and is the join type. The frequency of each join pattern serves as edge weight in G.
Metadata Generation. The logs reveal which tables and columns exist, but not what they mean. Names like d_wfm_fclty_pop_dfntn_mnl offer little semantic guidance. We prompt an LLM with representative queries referencing each table T to generate synthetic metadata describing table purpose, column semantics, and typical usage patterns (Appendix B.1).
Entity Extraction. From the generated metadata , we extract domain entities representing business concepts associated with each table (Appendix B.3). For example, entities for an attendance table might include {employee, time-off, approval rate}. These entities bridge the vocabulary gap between user questions and schema elements.
The resulting graph G has nodes V representing tables (annotated with metadata and entities) and edges E representing join relationships (weighted by frequency).
4.2 Entity-Driven Retrieval
Given a question Q, we retrieve relevant context from G through entity matching, graph traversal, and structural ranking.
Entity Matching. Embedding similarity between questions and table descriptions struggles with domain-specific terminology (Chen et al., 2026). Users ask about “shift swaps” or “approval rates,”

Figure 2: System architecture. Offline: query logs are processed to construct a knowledge graph encoding table metadata, domain entities, and join relationships. Online: given a question, we extract entities, traverse the graph to retrieve relevant context, and generate SQL.
not d_shift_swp_agg. We extract entities from the question using the same extraction process applied during graph construction, then match against table entities:
Tables with high entity overlap become seed nodes for graph traversal.
Multi-Strategy Scoring. Entity matching alone may miss relevant tables when terminology varies. We combine three signals:
where , measures embedding similarity between Q and , and scores tables appearing in historical queries similar to Q. We set to prioritize entity matching while retaining fallback strategies.
Graph Traversal. Starting from high-scoring seed tables, we traverse G to discover additional tables connected through join relationships. We perform breadth-first search up to k hops, scoring each path by entity coverage and join frequency:
where is the edge weight (join frequency) and balances entity coverage against established join patterns. This discovers tables not directly mentioned in the question but necessary for complete SQL construction.
Structural Ranking. To identify bridge tables connecting query-relevant entities, we apply Personalized PageRank with seed tables as the personalization vector. Tables with high PPR scores serve structural roles in the database even if not directly matched by entities.
4.3 Context Assembly and SQL Generation
The retrieval stage yields a set of relevant tables with their metadata, entity mappings, and join paths. We assemble these into a structured context for SQL generation.
Context Structure. The context comprises three components: (1) table metadata including descriptions and column information, (2) join paths derived from historical patterns, and (3) similar historical queries serving as few-shot examples (Appendix C.2). This hierarchical organization foregrounds the most relevant information for the LLM.
SQL Generation. We prompt an LLM with the question Q and assembled context to generate SQL (Appendix B.4):
where instructs the model to use only tables and columns present in the provided metadata, implement joins according to the identified paths, and avoid hallucinating schema elements. This grounding in retrieved context is critical: without it, LLMs frequently generate plausible but invalid SQL referencing non-existent columns (Chen et al., 2026).
4.4 Implementation
We process query logs from an enterprise production system spanning 240 tables. Knowledge graph construction uses Claude 3.7 Sonnet (temperature 0) for metadata generation and entity extraction, implemented in NetworkX. Entity matching combines exact match ( ), substring match ( ), and semantic similarity ( ) using E5-base-v2. Graph traversal is limited to k = 5 hops.
5 Evaluation Framework
Traditional text-to-SQL metrics assume a single correct answer, which holds for deterministic questions with fully specified constraints. However, enterprise questions are frequently underspecified: Spider 2.0 notes that “questions do not explicitly specify which columns to return” (Lei et al., 2025), and BEAVER observes that real analyst questions admit multiple valid SQL formulations (Chen et al., 2026). We therefore adopt a multi-faceted evaluation that extends traditional metrics to handle open-ended questions, combining execution-based metrics with LLM-as-judge assessment validated against human expert annotations.
Metrics. We evaluate along three dimensions. Execution validity measures whether SQL runs without errors, providing a necessary but insufficient quality signal. LLM-as-judge pairwise comparison presents two SQL queries blindly (randomized A/B assignment) and scores executability, schema validity, filter correctness, join relevance, and result fidelity (Appendix B.5). We validate this automated evaluation against annotations from two senior data engineers on our Amazon deployment, finding 83% agreement on cases with clear human preference (§6.3). Rubric-based scoring decomposes SQL quality into interpretable dimensions for fine-grained analysis.
Baseline. State-of-the-art text-to-SQL systems require complete schema information unavailable in our setting, and even with reconstructed documentation, their schema linking struggles without historical usage patterns (Appendix H). We compare against an embedding-based RAG baseline operating under identical constraints, with implementation details in §6.
6 Experiments
We evaluate on two settings: an internal Amazon deployment with expert validation, and the public BEAVER benchmark for reproducibility.
| Metric | Ours | RAG |
|---|---|---|
| Execution Validity | 200/209 (95.7%) | 127/209 (60.8%) |
| LLM Judge Wins | 95 (45.5%) | 71 (34.0%) |
| Rubric Judge Wins | 100 (47.8%) | 64 (30.6%) |
Table 1: BEAVER benchmark results (209 questions). Ties: 21 both adequate (LLM), 45 both (Rubric).
6.1 Experimental Setup
We evaluate on two complementary settings: our Amazon deployment demonstrates real-world value with expert validation but cannot be independently reproduced, while BEAVER provides a public benchmark with gold SQL, enabling reproducible comparison and generated-vs-gold analysis.
Amazon Internal Deployment. We deploy on a production analytics database with 240 frequently-queried tables selected from thousands available, processing approximately 500K historical queries with zero schema documentation. The constructed knowledge graph contains 1,847 join edges extracted from query patterns. For evaluation, we use 35 test questions: 25 LLM-generated for coverage across table combinations, and 10 curated by subject matter experts reflecting real business needs. Two data engineers performed blind evaluation of SQL pairs.
BEAVER Benchmark. BEAVER (Chen et al., 2026) provides 209 questions across enterprise databases with 463 tables. Since BEAVER supplies schema files rather than query logs, we generate equivalent metadata from schema documentation to match our pipeline input format (Appendix E). Our adaptation discovers 1,113 implicit joins beyond the 127 declared relationships, yielding 1,310 total knowledge graph edges (Table 6).
Baseline. Our RAG baseline embeds table metadata using E5-base-v2, retrieves top-12 tables via cosine similarity, and generates SQL with Claude 3.7 Sonnet. Both systems receive identical generated metadata; the difference is retrieval strategy.
6.2 Main Results
Table 1 summarizes performance on BEAVER. Our approach achieves execution validity compared to for RAG, a 35-point improvement demonstrating that knowledge graph structure produces coherent table-column combinations.
In blind pairwise comparison, LLM judges prefer our system in of cases versus
| Dimension | Ours | RAG | Both |
|---|---|---|---|
| Executability | 74 | 1 | 126 |
| Schema Validity | 60 | 17 | 132 |
| Filter Correctness | 52 | 28 | 120 |
| Join Relevance | 44 | 55 | 62 |
| Result Fidelity | 85 | 69 | 38 |
Table 2: Rubric dimension wins on BEAVER test set.
| Evaluator | Ours | RAG |
|---|---|---|
| Expert Consensus | 70% | 10% |
| LLM Judge | 80% | 16% |
| LLM-Human Agreement | 83% | |
Table 3: Amazon evaluation. Remaining cases are ties.
for RAG. The rubric-based judge shows consistent preference (47.8% vs 30.6%). Table 2 breaks down by dimension: our largest gains appear in executability (+74 vs +1) and schema validity (+60 vs +17), directly validating that KG-guided retrieval reduces hallucinated columns.
6.3 Human Validation
To establish that LLM-as-judge reflects real-world utility, we compare judgments against expert annotations on our Amazon deployment. Table 3 shows both data engineers and LLM judges strongly prefer our system (70% vs 10% for experts, 80% vs 16% for LLM). On questions where humans expressed clear preference, LLM judgments agreed in 83% of cases, validating automated evaluation as a reliable proxy for expert assessment.
6.4 Rethinking Gold Standards
A key motivation for our evaluation framework is that enterprise questions often admit multiple valid SQL formulations, making “gold” answers one reasonable solution among many. To test this empirically, we compare our generated SQL against human-written gold SQL from BEAVER using the same blind evaluation protocol.
Table 4 reveals a striking pattern. On open-ended questions where interpretation varies, our system achieves quality scores that exceed gold (9.00 vs 8.85). In pairwise comparison, judges find our SQL adequate or better in 46% of open-ended cases. On deterministic questions with clear correct answers, gold appropriately dominates.
This finding validates our evaluation approach: for the substantial portion of enterprise questions that are inherently open-ended, traditional gold-based metrics penalize valid alternative formulations. SQL that judges rate 9.0/10 should not be
| Deterministic (n=114) | Open-Ended (n=95) | |
|---|---|---|
| Gold Avg Score | 8.50 | 8.85 |
| Ours Avg Score | 7.55 | 9.00 |
| Gold Wins | 64.9% | 61.1% |
| Ours Wins | 26.3% | 28.4% |
| Both Adequate | 3.5% | 7.4% |
Table 4: Generated vs Gold SQL by question type. On open-ended questions, generated SQL matches or exceeds gold quality.
| Configuration | Score | Δ | vs Full |
|---|---|---|---|
| Full Pipeline | 7.76 | - | - |
| - Entity Matching | 7.34 | -5.4% | 43% / 21% |
| - KG Traversal | 7.60 | -2.1% | 41% / 28% |
| - PPR Ranking | 7.62 | -1.7% | 21% / 18% |
Table 5: Ablation on BEAVER. Score: open-ended evaluation (0–10). vs Full: pairwise wins (Full / Ablated).
considered wrong simply because it differs from one particular gold answer. Full breakdown by question type and database appears in Appendix F.
6.5 Ablation Studies
We isolate component contributions by removing each from the full pipeline (Table 5). Entity matching shows the largest impact: removing it drops scores by 5.4% and loses 43% of pairwise comparisons. This confirms that domain terminology requires explicit entity grounding beyond embedding similarity.
KG traversal contributes 2.1%, validating that graph navigation discovers necessary tables not directly matched by entities. PPR ranking provides modest gains with 60.8% ties, suggesting it refines rather than fundamentally changes retrieval. Per-dimension analysis (Appendix E.3) shows entity matching mostly impacts result fidelity, while KG traversal primarily affects join relevance.
7 Conclusion
We presented a text-to-SQL framework that operates without schema documentation by mining query logs to construct a knowledge graph of table relationships and domain entities. Entity-driven GraphRAG retrieval bridges the vocabulary gap between business terminology and cryptic schema identifiers, substantially outperforming embedding-based baselines. Our results demonstrate effective text-to-SQL in schema-ambiguous enterprise environments, while highlighting the need for evaluation beyond single-gold matching.
8 Limitations
The BEAVER adaptation uses schema-derived rather than log-derived edges, which lack frequency information and may include relationships absent from actual usage patterns.
References
Ruisheng Cao, Lu Chen, Zhi Chen, Yanbin Zhao, Su Zhu, and Kai Yu. 2021. Lgesql: Line graph enhanced text-to-sql model with mixed local and non-local relations. Preprint, arXiv:2106.01093.
Surajit Chaudhuri and Vivek R. Narasayya. 1997. An efficient cost-driven index selection tool for microsoft sql server. In Proceedings of the 23rd International Conference on Very Large Data Bases, VLDB '97, page 146–155, San Francisco, CA, USA. Morgan Kaufmann Publishers Inc.
Peter Baile Chen, Devin Yang, Weiyue Li, Fabian Wenz, Yi Zhang, Nesime Tatbul, Michael Cafarella, Çağatay Demiralp, and Michael Stonebraker. 2026. Beaver: An enterprise benchmark for text-to-sql. Preprint, arXiv:2409.02038.
Zui Chen, Han Li, Xinhao Zhang, Xiaoyu Chen, Chunyin Dong, Yifeng Wang, Xin Cai, Su Zhang, Ziqi Li, Chi Ding, Jinxu Li, Shuai Wang, Dousheng Zhao, Sanhai Gao, and Guangyi Liu. 2025. Rubiksql: Lifelong learning agentic knowledge base as an industrial nl2sql system. Preprint, arXiv:2508.17590.
Xuemei Dong, Chao Zhang, Yuhang Ge, Yuren Mao, Yunjun Gao, lu Chen, Jinshu Lin, and Dongfang Lou. 2023. C3: Zero-shot text-to-sql with chatgpt. Preprint, arXiv:2307.07306.
Jeffrey Eben, Aitzaz Ahmad, and Stephen Lau. 2025. Rasl: Retrieval augmented schema linking for massive database text-to-sql. Preprint, arXiv:2507.23104.
Darren Edge, Ha Trinh, Newman Cheng, Joshua Bradley, Alex Chao, Apurva Mody, Steven Truitt, Dasha Metropolitansky, Robert Osazuwa Ness, and Jonathan Larson. 2025. From local to global: A graph rag approach to query-focused summarization. Preprint, arXiv:2404.16130.
Dawei Gao, Haibin Wang, Yaliang Li, Xiuyu Sun, Yichen Qian, Bolin Ding, and Jingren Zhou. 2023. Text-to-sql empowered by large language models: A benchmark evaluation. Preprint, arXiv:2308.15363.
Dongjun Lee, Choongwon Park, Jaehyuk Kim, and Heesoo Park. 2024. Mcs-sql: Leveraging multiple prompts and multiple-choice selection for text-to-sql generation. Preprint, arXiv:2405.07467.
Fangyu Lei, Jixuan Chen, Yuxiao Ye, Ruisheng Cao, Dongchan Shin, Hongjin Su, Zhaoqing Suo, Hongcheng Gao, Wenjing Hu, Pengcheng Yin, Victor
Zhong, Caiming Xiong, Ruoxi Sun, Qian Liu, Sida Wang, and Tao Yu. 2025. Spider 2.0: Evaluating language models on real-world enterprise text-to-sql workflows. Preprint, arXiv:2411.07763.
Haoyang Li, Jing Zhang, Cuiping Li, and Hong Chen. 2023a. Resdsql: Decoupling schema linking and skeleton parsing for text-to-sql. Preprint, arXiv:2302.05965.
Haoyang Li, Jing Zhang, Hanbing Liu, Ju Fan, Xiaokang Zhang, Jun Zhu, Renjie Wei, Hongyan Pan, Cuiping Li, and Hong Chen. 2024. Codes: Towards building open-source language models for text-to-sql. Preprint, arXiv:2402.16347.
Jinyang Li, Binyuan Hui, Ge Qu, Jiaxi Yang, Binhua Li, Bowen Li, Bailin Wang, Bowen Qin, Rongyu Cao, Ruiying Geng, Nan Huo, Xuanhe Zhou, Chenhao Ma, Guoliang Li, Kevin C. C. Chang, Fei Huang, Reynold Cheng, and Yongbin Li. 2023b. Can llm already serve as a database interface? a big bench for large-scale database grounded text-to-sqls. Preprint, arXiv:2305.03111.
Mohammadreza Pourreza, Hailong Li, Ruoxi Sun, Yeounoh Chung, Shayan Talaei, Gaurav Tarlok Kakkar, Yu Gan, Amin Saberi, Fatma Ozcan, and Sercan O. Arik. 2024. Chase-sql: Multi-path reasoning and preference optimized candidate selection in text-to-sql. Preprint, arXiv:2410.01943.
Mohammadreza Pourreza and Davood Rafiei. 2023. Din-sql: Decomposed in-context learning of text-to-sql with self-correction. Preprint, arXiv:2304.11015.
Vladislav Shkapenyuk, Divesh Srivastava, Theodore Johnson, and Parisa Ghane. 2025. Automatic metadata extraction for text-to-sql. Preprint, arXiv:2505.19988.
Bailin Wang, Richard Shin, Xiaodong Liu, Oleksandr Polozov, and Matthew Richardson. 2021. Rat-sql: Relation-aware schema encoding and linking for text-to-sql parsers. Preprint, arXiv:1911.04942.
Tao Yu, Rui Zhang, Kai Yang, Michihiro Yasunaga, Dongxu Wang, Zifan Li, James Ma, Irene Li, Qingning Yao, Shanelle Roman, Zilin Zhang, and Dragomir Radev. 2018. Spider: A large-scale human-labeled dataset for complex and cross-domain semantic parsing and text-to-SQL task. In Proceedings of the 2018 Conference on Empirical Methods in Natural Language Processing, pages 3911–3921, Brussels, Belgium. Association for Computational Linguistics.
Kun Zhang, Xiexiong Lin, Yuanzhuo Wang, Xin Zhang, Fei Sun, Cen Jianhe, Hexiang Tan, Xuhui Jiang, and Huawei Shen. 2023. ReFSQL: A retrieval-augmentation framework for text-to-SQL generation. In Findings of the Association for Computational Linguistics: EMNLP 2023, pages 664–673, Singapore. Association for Computational Linguistics.
A Appendix
B Prompts
This appendix provides the prompts used in knowledge graph construction, SQL generation, and evaluation.
B.1 Metadata Generation Prompt
Metadata Generation
Given the table [TABLE_NAME] which appears in [N] queries, and the following representative queries:
[SAMPLE_QUERIES]
Generate metadata describing:
-
Table purpose and business context
-
Column names, meanings, and likely data types
-
Primary/foreign key columns
-
Common join patterns with other tables
-
Typical filtering and aggregation patterns
Format as JSON with fields: table_name, description, columns (list with name, description, type), key_columns, common_joins, common_filters.
B.2 Join Relationship Extraction Prompt
Join Relationship Extraction
Extract table join relationships from the following SQL query. Identify ALL relationships, including implicit ones.
SQL Query: [SQL_QUERY]
Tables referenced: [TABLE_LIST]
Consider the following relationship types:
-
Explicit joins (JOIN, LEFT JOIN, INNER JOIN)
-
Implicit joins in WHERE clauses
-
Relationships through CTEs where tables share keys
-
Logical data flow beyond syntax
For each relationship, return: left_table, right_table, join_type, join_conditions, relationship_type (EXPLICIT or IM-PLICIT).
B.3 Entity Extraction Prompt
Entity Extraction
You are an expert entity extractor for enterprise data systems.
WHAT TO EXTRACT
• Core business concepts (e.g., shift swap, approval rate, employee)
• Processes (e.g., registration, scheduling, approvals)
• Organizational entities (e.g., facility, department, site)
• Primary metrics (e.g., counts, rates, hours)
WHAT TO AVOID
• Specific IDs or literal values
• Dates or absolute time ranges
• Generic database terms (table, record, row)
Extract concise noun phrases (1–3 words). Preserve business acronyms.
Input: [TABLE_METADATA]
Output: Return only a valid JSON array of entity strings.
B.4 SQL Generation Prompt
SQL Generation
Generate a SQL query for the following question using ONLY the tables and columns in the provided context.
Context: [TABLE_METADATA] [JOIN_PATHS]
[SIMILAR_QUERIES]
Question: [USER_QUESTION]
Instructions:
-
Use ONLY tables and columns explicitly listed in the metadata
-
If a needed column is not in the metadata, explain the limitation
-
Follow join patterns from the provided join paths
-
Use table aliases consistently
-
Do NOT hallucinate tables or columns
B.5 LLM-as-Judge Pairwise Comparison
We employ blind pairwise comparison where an LLM judge evaluates two SQL queries without knowing their source. A/B assignment is randomized across comparisons to prevent systematic bias.
Pairwise SQL Comparison
Compare two SQL queries (blind evaluation). You are NOT told which system produced each SQL.
Inputs: [QUESTION], [SQL_A], [SQL_B], [EXEC_A], [EXEC_B], [METADATA]
Score 0–2 on four dimensions:
-
Schema Validity: Tables/columns exist and are appropriate
-
Filter Correctness: WHERE/GROUP BY/LIMIT reflect constraints
-
Join Relevance: Joins are plausible and necessary
-
Result Fidelity: Output satisfies the information need
If SQL fails to execute, score 0 on all dimensions.
Return JSON: dimensions, total_score_A, total_score_B, overall_winner (AlBbothneither), overall_rationale.
B.6 Open-Ended Scoring Rubric
For questions where multiple interpretations are valid, we assess how well SQL addresses the question’s intent rather than matching a specific gold formulation.
Open-Ended SQL Evaluation
Score the SQL on a 0–10 scale. Focus on whether the SQL fulfills the intent of the question, not whether it exactly matches any gold answer.
Question: [QUESTION]
SQL: [SQL]
Execution Result: [EXEC_RESULT]
Scoring rubric:
-
Executability (0–2): 2=executes successfully, 1=minor fixable error, 0=fails
-
Table/Join Relevance (0–2): 2=clearly aligned, 1=partial, 0=unrelated
-
Field Coverage (0–3): 3=all key fields, 2=most, 1=some, 0=none
-
Output Usefulness (0–2): 2=answers question, 1=partial, 0=not useful
-
Interpretation Quality (0–1): 1=reasonable interpretation of ambiguous terms
Important: For open-ended questions, reward reasonable interpretations.
Return JSON: score, subscores, verdict (yes|partial|no), rationale, issues.
B.7 Question Type Classification
We classify questions into two categories to enable stratified analysis of system performance under different levels of ambiguity:
Question Type Classification
Classify [QUESTION] into one of two categories:
- Deterministic: Fully specifies all constraints and required fields; essentially one correct SQL formulation exists.
Examples: “Total revenue for product ID 123 in Q3 2024?” / “List employees in department 5 hired before 2020.”
- Open-Ended: Underspecified or ambiguous; multiple valid SQL formulations could satisfy the intent.
Examples: “Show top performing products.” (How many? By what metric?) / “Analyze attendance trends.” (What granularity?)
Return: Category name and brief justification.
On BEAVER, this classification yields 114 deterministic questions and 95 open-ended questions. The prevalence of open-ended questions (45%) motivates our multi-faceted evaluation framework, nearly half of enterprise questions cannot be fairly evaluated against a single gold standard.
C Data Formats
C.1 Knowledge Graph Triplet Format
Each edge in the knowledge graph stores join relationships as triplets:
Triplet Structure
{ "left_table": "schema.employees", "right_table": "schema.attendance", "join_type": "INNER", "join_conditions": "employees.id = attendance.emp_id", "relationship_type": "EXPLICIT", "frequency": 342, }
"left_table_entities": ["employee", "worker"], "right_table_entities": ["attendance", "time-off"], "shared_entities": ["employee"] }
C.2 Context Assembly Format
The context provided to the LLM for SQL generation is structured hierarchically:
Context Structure
1. Table Metadata
Table: shift_swap_agg Description: Aggregated shift swap metrics by month and facility Columns:
- date_trunc_month: DATE | Month of record
- facility_id: VARCHAR | Facility identifier
- nbr_swap_request: INT | Total swap requests
- nbr_swap_approved: INT | Approved requests
2. Join Paths
shift_swap_agg.facility_id -> facility_dim.facility_id (freq: 847)
3. Similar Queries
Q: "What was the approval rate last month?" SQL: SELECT SUM(nbr_swap_approved) * 100.0 / SUM(nbr_swap_request) FROM shift_swap_agg WHERE date_trunc_month = DATE '2025-06-01'
D BEAVER Benchmark Adaptation
BEAVER (Chen et al., 2026) provides schema files rather than query logs, requiring adaptation to evaluate our approach on a reproducible benchmark. This section details the conversion pipeline that enables controlled experiments while maintaining methodological consistency.
D.1 Motivation for Adaptation
Our primary evaluation on Amazon internal data demonstrates practical value but cannot be independently reproduced. BEAVER offers complementary benefits: (1) a public test set enabling reproducible comparison, (2) gold SQL annotations for measuring accuracy against expert solutions, and (3) diverse database domains (academic data warehouse, OpenStack infrastructure). However, BEAVER lacks the query logs central to our approach.
We address this gap by generating equivalent metadata from BEAVER’s schema files, constructing a knowledge graph that mirrors the structure our pipeline would produce from logs. This tests whether entity-driven GraphRAG generalizes beyond the log-based setting while enabling direct comparison against gold SQL.
D.2 Schema-to-Metadata Conversion
BEAVER provides structured schema files containing table names, column definitions, data types, and declared foreign keys. We convert these to our metadata format through three steps:
Step 1: Table Metadata Generation. For each of BEAVER's 463 tables, we generate synthetic metadata using the same LLM prompting approach as our main pipeline. The prompt receives the table name, column names and types, and any schema descriptions provided by BEAVER. The output includes table purpose descriptions, column semantics, and inferred usage patterns.
Step 2: Join Relationship Discovery. BEAVER declares only 127 explicit foreign key relationships across its databases—far fewer than typical enterprise usage would reveal. To construct a realistic knowledge graph, we discover implicit joins through:
-
Column name matching: Identify candidate pairs where columns share naming patterns (e.g., *_KEY, *_ID)
-
LLM validation: For each candidate pair, prompt an LLM to assess whether the relationship represents a valid join based on table semantics
-
Confidence filtering: Accept joins with low/medium/high confidence ratings
This process discovered 1,113 implicit joins beyond the 127 declared relationships, yielding a knowledge graph with 1,310 total edges across 463 tables. Table 6 summarizes the construction statistics.
Step 3: Entity Extraction. We extract domain entities from generated metadata using the same prompt as our main pipeline (Appendix B.3). Entities are normalized to lowercase and deduplicated. The resulting 1,844 unique entities enable
| Statistic | Value |
|---|---|
| Total tables | 463 |
| Explicit FK relationships | 127 |
| Implicit joins discovered | 1,113 |
| Total KG edges | 1,310 |
| Unique entities extracted | 1,844 |
Table 6: BEAVER knowledge graph construction statistics.
the entity-driven retrieval that differentiates our approach from similarity-based baselines.
D.3 Implicit Join Validation
The implicit join discovery uses an LLM to validate candidate relationships:
Implicit Join Validation
Assess whether two tables should be joined based on shared column names and table semantics.
Left Table: [LEFT_TABLE_NAME]
[LEFT_TABLE_METADATA]
Right Table: [RIGHT_TABLE_NAME]
[RIGHT_TABLE_METADATA]
Candidate Join Column: [COLUMN_NAME]
Determine if this represents a valid join relationship. Consider:
• Do the tables share a logical relationship?
• Does the column semantically connect both tables?
• Would this join be meaningful for analytical queries?
Return JSON: is_join (boolean), confidence (lowmediumhigh), explanation.
D.4 Limitations of Adaptation
The schema-based adaptation differs from log-based construction in important ways:
• No frequency information: All edges receive equal weight (1.0) rather than usage-derived frequencies
• Synthetic relationships: LLM-validated joins may include relationships that would never appear in actual queries
• Missing query patterns: No historical queries available for few-shot examples
Despite these limitations, BEAVER results demonstrate that entity-driven GraphRAG provides value even without query logs, suggesting the approach generalizes beyond the log-based setting.
E Experimental Details
E.1 Dataset Statistics
Table 7 summarizes both evaluation settings.
| Amazon | BEAVER | |
|---|---|---|
| Total Tables | 240 | 463 |
| Query Logs | ~500K | - |
| KG Join Edges | 1,847 | 1,310 |
| Test Questions | 35 | 209 |
| Deterministic | - | 114 |
| Open-Ended | - | 95 |
| Gold SQL Available | No | Yes |
Table 7: Dataset statistics for both evaluation settings.
E.2 Table Selection Statistics
Table 8 compares retrieval behavior between our system and the RAG baseline on BEAVER.
| Metric | Ours | RAG |
|---|---|---|
| Avg tables selected | 12.61 | 12.00 |
| Median | 13 | 12 |
| Min / Max | 5 / 16 | 12 / 12 |
| % of total (463) | 2.72% | 2.59% |
Table 8: Table selection statistics on BEAVER. Our system adaptively selects 5–16 tables based on query complexity; RAG uses fixed top-k=12.
Our system's adaptive selection (5–16 tables) reflects query complexity, while RAG's fixed retrieval cannot adjust to simpler or more complex questions.
E.3 Ablation Configuration Details
Each ablation removes a single component while keeping others intact:
• – Entity Matching: Relies only on embedding similarity; entity overlap score set to zero.
• – KG Traversal: Retrieves only directly-matched tables; disables BFS from seed nodes.
• – PPR Ranking: Uses raw scores without Personalized PageRank reranking.
Table 9 shows per-dimension rubric analysis for ablations.
| Ablation | Exec | Schema | Filter | Join | Result |
|---|---|---|---|---|---|
| - Entity | 16/11 | 21/11 | 28/19 | 37/22 | 75/42 |
| - KG Trav | 16/10 | 28/13 | 33/21 | 51/36 | 78/54 |
| - PPR | 13/12 | 14/10 | 15/14 | 17/12 | 41/34 |
Table 9: Ablation dimension breakdown (Full wins / Ablated wins). Entity matching has largest impact on result fidelity.
F Question Type Analysis
F.1 Generated vs Gold by Question Type
Table 10 shows detailed comparison by question type. On deterministic questions, gold SQL appropriately dominates. On open-ended questions, our system achieves comparable or superior quality, supporting our argument that traditional gold-based evaluation inadequately captures valid alternative formulations.
| Deterministic | Open-Ended | |||
|---|---|---|---|---|
| Gold | Ours | Gold | Ours | |
| Avg Score | 8.50 | 7.55 | 8.85 | 9.00 |
| Blind Judge Wins | 74 | 30 | 58 | 27 |
| Both Adequate | 4 | 7 | ||
| Rubric Judge Wins | 65 | 39 | 51 | 33 |
| Both Adequate | 10 | 11 | ||
Table 10: Generated vs Gold comparison by question type.
F.2 Ours vs RAG by Question Type
Table 11 shows consistent improvements across both question types, with larger margins on open-ended questions where entity grounding provides greater benefit.
| Deterministic | Open-Ended | |||
|---|---|---|---|---|
| Ours | RAG | Ours | RAG | |
| Avg Score | 7.54 | 6.76 | 8.99 | 8.65 |
| Exec Valid | 95.6% | 58.8% | 96.8% | 63.2% |
Table 11: Ours vs RAG by question type.
F.3 Per-Database Results
Table 12 shows consistent improvements across BEAVER's databases, with largest gains on the complex data warehouse (dw).
G Example Queries with Rubric Analysis
We present representative examples from Beaver generations, spanning high, medium, and low qual-
| Database | n | Ours Exec | RAG Exec | Δ |
|---|---|---|---|---|
| dw | 121 | 94.2% | 47.1% | +47.1 |
| csail_nova | 43 | 100% | 72.1% | +27.9 |
| csail_neutron | 30 | 100% | 93.3% | +6.7 |
| keystone | 8 | 100% | 100% | 0 |
| Other | 7 | 100% | 100% | 0 |
Table 12: Execution validity by database.
ity generations with full LLM rubric evaluations.
G.1 High Quality: Entity Matching Enables Correct Schema Selection
Example 1: Material Status Analysis — Score: 10/10
Question: What is material status, the total number of materials, subjects, schools, and most recent publication year for each material status?
Question Type: Deterministic
Generated SQL:
SELECT tms.TIP_MATERIAL_STATUS, COUNT(DISTINCT tm.TIP_MATERIAL_KEY) AS TotalMaterials, COUNT(DISTINCT td.SUBJECT_ID) AS TotalSubjects, COUNT(DISTINCT tso.OFFER_SCHOOL_NAME) AS TotalSchools, MAX(tm.YEAR) AS MostRecentPublicationYear FROM dw.TIP_MATERIAL_STATUS tms LEFT JOIN dw.TIP_DETAIL td ON tms.TIP_MATERIAL_STATUS_KEY = td. TIP_MATERIAL_STATUS_KEY LEFT JOIN dw.TIP_MATERIAL tm ON td.TIP_MATERIAL_KEY = tm.TIP_MATERIAL_KEY LEFT JOIN dw.TIP_SUBJECT_OFFERED tso ON td.TIP_SUBJECT_OFFERED_KEY = tso. TIP_SUBJECT_OFFERED_KEY GROUP BY tms.TIP_MATERIAL_STATUS
| Dimension | Score | Assessment |
|---|---|---|
| Executability | 2/2 | Executes successfully |
| Schema Validity | 2/2 | All tables/columns correct |
| Filter Correctness | 2/2 | GROUP BY properly applied |
| Join Relevance | 2/2 | Four-table join path correct |
| Result Fidelity | 2/2 | All requested fields returned |
| Total | 10/10 |
Verdict: yes — fully answers the question.
Analysis. Entity matching on “material status” → TIP_MATERIAL_STATUS, “subjects” → TIP_SUBJECT_OFFERED, and “schools” → OFFER_SCHOOL_NAME guided retrieval to correct schema elements. The knowledge graph provided the join path through TIP_DETAIL as a bridge table.
G.2 High Quality: KG Traversal Discovers Non-Obvious Tables
G.3 Medium Quality: Reasonable Interpretation of Ambiguous Question
Example 2: Mailing List Visibility — Score: 10/10
Question: For each mailing list, list its owner, owner type, member visibility ('Public Members' if public, 'Hidden Members' otherwise), and member count per visibility type. Include grand totals per owner.
Question Type: Deterministic
Generated SQL:
WITH ListVisibility AS ( SELECT ml.MOIRA_LIST_NAME, mld.MOIRA_LIST_KEY, mlo.OWNER, mlo.OWNER_TYPE, CASE WHEN ml.IS_PUBLIC = 'Y' THEN 'Public Members' ELSE 'Hidden Members' END AS MemberVisibility FROM dw.MOIRA_LIST AS ml JOIN dw.MOIRA_LIST_DETAIL AS mld ON ml.MOIRA_LIST_KEY = mld.MOIRA_LIST_KEY JOIN dw.MOIRA_LIST_OWNER AS mlo ON mld.MOIRA_LIST_OWNER_KEY = mlo.MOIRA_LIST_OWNER_KEY WHERE ml.IS_MOIRA_MAILING_LIST = 'Y' ), ListVisibilityCounts AS ( SELECT OWNER, OWNER_TYPE, MemberVisibility, COUNT(*) AS MemberCount FROM ListVisibility GROUP BY OWNER, OWNER_TYPE, MemberVisibility ), GrandTotal AS ( SELECT OWNER, OWNER_TYPE, NULL AS MemberVisibility, SUM(MemberCount) AS MemberCount FROM ListVisibilityCounts GROUP BY OWNER, OWNER_TYPE ) SELECT * FROM ListVisibilityCounts UNION ALL SELECT * FROM GrandTotal ORDER BY OWNER, OWNER_TYPE, MemberVisibility;
| Dimension | Score | Assessment |
|---|---|---|
| Executability | 2/2 | Complex CTEs execute correctly |
| Schema Validity | 2/2 | MOIRA tables correctly identified |
| Filter Correctness | 2/2 | IS_MOIRA_MAILING_LIST filter |
| Join Relevance | 2/2 | Three-table join path appropriate |
| Result Fidelity | 2/2 | Grand totals included as requested |
| Total | 10/10 |
Verdict: yes — comprehensive answer with correct structure.
Example 3: Computer Science Room Query — Score: 8/10
Question: List unique full room names, building names, addresses, cities, states, postal codes, and building heights for rooms associated with subjects Computer Science students can enroll in.
Question Type: Open-ended (“CS students can enroll” is ambiguous)
Generated SQL:
SELECT DISTINCT fr.ROOM_FULL_NAME, b.BUILDING_NAME, fba.STREET_NUMBER || ' ' || fba.STREET_NAME || ' ' || fba.STREET_SUFFIX AS STREET_ADDRESS, fba.CITY, fba.STATE, fba.POSTAL_CODE, fb.BUILDING_HEIGHT FROM dw.FCLT_ROOMS AS fr JOIN dw.BUILDINGS AS b ON fr.FCLT_BUILDING_KEY = b.BUILDING_KEY JOIN dw.FCLT_BUILDING_ADDRESS AS fba ON b.BUILDING_KEY = fba.FCLT_BUILDING_KEY JOIN dw.COURSE_CATALOG_SUBJECT_OFFERED AS ccso ON fr.FCLT ROOM_KEY = ccso.MEET_PLACE LEFT JOIN dw.FAC_BUILDING AS fb ON b.BUILDING_KEY = fb.FAC_BUILDING_KEY WHERE ccso.DEPARTMENT_NAME = 'Electrical Eng & Computer Sci'
| Dimension | Score | Assessment |
|---|---|---|
| Executability | 2/2 | Executes successfully |
| Schema Validity | 2/2 | All tables exist and relevant |
| Filter Correctness | 2/2 | Department filter reasonable |
| Join Relevance | 2/2 | Six-table join path correct |
| Result Fidelity | 1/2 | Interpretation differs from gold |
| Total | 8/10 |
Verdict: partial — answers a reasonable interpretation.
Issues: Filters by department rather than student enrollment eligibility; gold uses different interpretation involving major requirements.
Analysis. The question mentions “mailing list,” “owner,” and “visibility” but not tables MOIRA_LIST_DETAIL or MOIRA_LIST_OWNER. Entity extraction identified “mailing list” → MOIRA_LIST, and KG traversal discovered related tables through join edges.
Analysis. This exemplifies why open-ended evaluation is necessary. The SQL scores 8/10 and produces useful results, but “subjects CS students can enroll in” admits multiple interpretations: (a) subjects offered by CS department, (b) subjects CS majors must take, (c) subjects with no restrictions. Traditional exact-match would mark this wrong despite practical utility.
G.4 Low Quality: Missing Entity Coverage
Example 4: Mailing List Instructor Query — Score: 5/10
Question: For each course instructor in the 'keeper-zephyr' mailing list, provide mailing lists they subscribe to, instructor name, earliest/latest publication years, and total enrolled students.
Question Type: Deterministic
Generated SQL:
SELECT NULL AS mailing_list_name, LCI.INSTRUCTOR_NAME, NULL AS earliest_publication_year, NULL AS latest_publication_year, SUM(SO.SUBJECT_ENROLLMENT_NUMBER) AS total_enrolled FROM DW.LIBRARY_COURSE_INSTRUCTOR AS LCI JOIN DW.LIBRARY_RESERVE_MATRL_DETAIL AS LRMD ON LCI.LIBRARY_COURSE_INSTRUCTOR_KEY = LRMD.LIBRARY_COURSE_INSTRUCTOR_KEY JOIN DW.SUBJECT_OFFERED AS SO ON LRMD.SUBJECT_ID = SO.SUBJECT_ID WHERE LCI.DEPARTMENT = 'keeper-zephyr' GROUP BY LCI.INSTRUCTOR_NAME
| Dimension | Score | Assessment |
|---|---|---|
| Executability | 2/2 | Executes without errors |
| Schema Validity | 2/2 | Tables exist (but wrong ones) |
| Filter Correctness | 0/2 | Uses department, not mailing list |
| Join Relevance | 1/2 | Joins valid but miss MOIRA tables |
| Result Fidelity | 0/2 | Returns NULLs for key fields |
| Total | 5/10 |
Verdict: partial — executes but fails to answer.
Issues: Missing
MOIRA_LIST/MOIRA_LIST_MEMBER
tables; incorrectly interprets ‘keeper-zephyr’ as department filter; returns NULL for publication years.
Analysis. Entity extraction failed to connect “mailing list” to the MOIRA schema. The system recognized “instructor” and “enrolled students” but missed the link to mailing list membership. When questions span multiple domains (academic + mailing lists), entity coverage may be incomplete.
G.5 Failure Pattern Summary
| Failure Pattern | Count | % |
|---|---|---|
| Missing entity coverage | 12 | 40% |
| Disconnected graph regions | 10 | 33% |
| Ambiguous terminology | 5 | 17% |
| Schema name confusion | 3 | 10% |
Table 13: Failure pattern analysis on low-scoring BEAVER queries (n=30).
Implications. Entity coverage failures (40%) suggest expanding entity extraction through iterative refinement would yield largest improvements. Disconnected graph regions (33%) indicate implicit join discovery does not fully bridge all semantic relationships.
H Comparison with Schema-Aware Methods
To assess whether traditional text-to-SQL methods could work in our setting given reconstructed schema documentation, we evaluate DIN-SQL (Pourreza and Rafiei, 2023) on our Amazon deployment. DIN-SQL decomposes text-to-SQL into schema linking, query classification, SQL generation, and self-correction modules. We convert our generated metadata to Spider format, providing DIN-SQL with the same table and column descriptions available to our system.
Setup. We run DIN-SQL on all 240 tables using the converted schema. Evaluation uses blind LLM-as-judge pairwise comparison, identical to our main experiments.
Results. Our system wins 72% of comparisons, DIN-SQL wins 12%, with 16% ties. This gap persists despite DIN-SQL receiving complete schema documentation with human-readable descriptions.
The limitation lies in schema linking: DIN-SQL must map question terms to schema elements for each query independently, without knowledge of which tables are commonly queried together or how domain terminology has historically mapped to schema elements. Our knowledge graph captures these patterns, accumulated from 500K historical queries, enabling more reliable retrieval when users employ business terminology that doesn't directly match schema names. This finding suggests that enterprise text-to-SQL benefits from retrieval grounded in historical usage patterns rather than per-query schema linking alone.