Sgu SQL
Sgu SQL
Qinggang Zhang 1 Hao Chen 2 Junnan Dong 1 Shengyuan Chen 1 Feiran Huang 3 Xiao Huang 1
1
Structure-Guided Large Language Models for Text-to-SQL Generation
• We identify the limitations of LLM-based Text-to-SQL 3.1. Revisiting User Query and Database via Graph
models and introduce SGU-SQL, which breaks down the
Bridging the gap between textual queries and the struc-
complex generation task in a syntax-aware manner. This
tured database poses several challenges. Firstly, construct-
ensures that the generated queries maintain both semantic
ing an accurate structure that captures the relationships be-
accuracy (correctly capturing user intentions) and syntac-
tween query terms and database entities is a non-trivial task.
tic correctness (following proper SQL structure).
Secondly, linking the query to the appropriate tables and
• SGU-SQL proposes graph-based structure construction to columns in the database is challenging, especially when
comprehend user query and database structure and then there is ambiguity or a lack of explicit connections. In
link query and database with dual-graph encoding. this paper, we build a comprehensive query-schema graph
designed to structure the query concept, the schema, and pre-
• SGU-SQL introduces tailored structure-decomposed gen- defined relations between the query phrases and the tables
eration strategies to decompose queries with syntax trees or columns present within the schema. The graph contains
and then incrementally generate accurate SQL with LLM. three key structures: (i) Query Structure (Rq ): Encodes
dependencies between tokens in the question, derived from
• Experiments on two benchmarks verify that SGU-SQL its syntactic parse. (ii) Database Structure (Rs ): Repre-
outperforms state-of-the-art baselines, including 11 fine- sents intrinsic relationships within the database schema, like
tuning models, 7 structure learning models, and 14 in- foreign keys. (iii) Linking Structure (Rl ): Aligns query
context learning models. entities with the columns or tables in the database.
2
Structure-Guided Large Language Models for Text-to-SQL Generation
User Query:
Semantic Dependency
R
What is the id of the semester
that had both Masters and
Bachelors students enrolled? SELECT
Syntactic Dependency
Query Graph
A R
FILTER
User Query
C T
CREATE TABLE `Transcript_Contents` (
Database Schema
`student_course_id`
CREATE TABLE INTEGER NOT NULL,
A
`Student_Enrolment_Courses
`transcript_id` INTEGER NOT NULL,
`
R Result Decomposing Tasks
(
C T
FOREIGN KEY (`student_course_id`)
`student_course_id` INTEGER
REFERENCES
PRIMARY KEY,
A Start Sub-Tasks 1
`course_id` INTEGER NOT NULL,
`Student_Enrolment_Courses`(`student_cou
`student_enrolment_id` INTEGER NOT
rse_id`),
C Column
NULL,
FOREIGN
FOREIGN KEYKEY
(`transcript_id`)
(`course_id`)
REFERENCES `Courses`(`course_id`),
T Table
REFERENCES `Transcripts`(`transcript_id`)
D.B. Schema Schema Graph
FOREIGN KEY
); (`student_enrolment_id`)
Sub-Tasks 2
REFERENCES
`Student_Enrolment`(`student_enrolmen
t_id`)
);
Dual Graph Encoding Syntax-based Decomposing Prompts
3.1.1. U SER Q UERY U NDERSTANDING AND where P (qi | q) is the probability of interpretation qi given
R EPRESENTATION the original query q.
A query graph can be depicted as Gq = (Vq , Rq ), where Natural language queries may contain multiple mentions of
Vq denotes the node set that characterizes the keywords the same entity, which need to be resolved to construct an
specified in the question, and Rq signifies the relationships accurate graph representation. Let M be the set of entities
among these keywords. To differentiate the relationship mentioned in the query and E be the set of unique entities.
between various words, we establish three separate link The coreference resolution can be formulated as finding a
categories, including Forward-Syntax, Backward-Syntax mapping function ϕ : M → E that maps each mention to
and None-Syntax relations to encapsulate the particular syn- its corresponding entity:
tactic connections among words in the vernacular question. ϕ(m) = argmaxe∈E P (e | m), (3)
a) Query Parsing: Syntactic parsing can help resolve struc- where P (e | m) is the probability of entity e given the
tural ambiguities in the query by providing a hierarchical mentioned entity m.
representation of the sentence structure. Specifically, we
first define a context-free grammar Gq for the query lan- c) Query Graph Construction: Once the syntax tree Tq is ob-
guage: tained, we can construct the graph structure Gq = (Vq , Eq )
Gq = (Nq , Σq , Pq , Sq ), (1) representing the user query. The vertices Vq = Vq is the set
of query concepts and terms and edges Eq are defined as
where Nq is a finite set of non-terminal symbols represent-
follows:
ing query concepts. Σq is a finite set of terminal symbols
representing query terms. Pq is a finite set of production Eq = Eq ∪ (vi , vj ) | vi , vj ∈ Vq ∧ relation(vi , vj ). (4)
rules that map non-terminals to sequences of terminals and
non-terminals. Sq ∈ Nq is the start symbol. The edges Eq in the graph structure include both the syntac-
tic relationships from the syntax tree and additional edges
The production rules Pq define the syntactic structure of the
based on semantic relationships between query concept-
query language.
s/terms. The resulting graph structure Gq captures both
Parsing a user query Q using the grammar Gq yields a the syntactic structure of the user query and the semantic
syntax tree Tq = (Vq , Eq ), where Vq is the set of vertices relationships between query concepts/terms.
representing query concepts. Eq ∈ Rq is the set of edges
representing syntactic relationships between the query con- 3.1.2. DATABASE U NDERSTANDING AND
cepts. R EPRESENTATION
b) Coreference resolution: Natural language queries often To generate accurate SQL queries, text-to-SQL systems
contain ambiguities, such as polysemy (words with multiple also need to have a comprehensive understanding of the
meanings) and syntactic ambiguity (multiple possible syntax database structure, including table names, column names,
trees). Let Q be the set of all possible interpretations of a and relationships between or across various tables/columns.
query q. The ambiguity challenge can be formulated as Representing and encoding the database in a way that can be
selecting the most likely interpretation q̂ from Q: effectively utilized by the text-to-SQL model is a challeng-
ing task. In this paper, we introduce a schema graph to rep-
q̂ = arg max P (qi | q), (2) resent database structure. Specifically, let D be a database
qi ∈Q
3
Structure-Guided Large Language Models for Text-to-SQL Generation
consisting of a set of tables T = T1 , T2 , . . . , Tn . Each table the structure of the database schema, with vertices repre-
Ti ∈ T has a set of columns Ci = {Ci1 , Ci2 , . . . , Cim }. We senting tables and columns and edges representing their re-
define a database schema graph Gd = (Vd , Rd ) to represent lationships. By combining the syntax tree with the schema
the structure of the database schema, where S denotes the graph through the mapping function ϕ, we establish a link
set of nodes representing tables and columns, and Rd is the between the query concepts/terms and the corresponding
set of edges representing the relationships between them. schema elements. This mapping allows us to identify which
tables and columns in the database are relevant to the user
a) Node Representation: Each table Ti ∈ T is represented as
query, enabling more accurate and targeted querying.
a node vTi ∈ S in the schema graph. Similarly, each column
Cij ∈ Ci of table Ti is represented as a node vCij ∈ S. The Specifically, given the constructed query and database
set of nodes S in the schema graph is defined as: graphs, we value the adjacency information during the
matching process and propose to automatically build the
S = vTi | Ti ∈ T ∪ vCij | Cij ∈ Ci , Ti ∈ T . (5) connection between the query structure and schema at the
node level. Specifically, we design a tailored structure-based
b) Edge Representation: The relationships between tables linking framework. Both query and schema structures are
and columns in the database schema are represented as first encoded through a Relational Graph Attention Network
edges in the schema graph. We define the following three (RGAT) (Busbridge et al., 2019) for initial node representa-
types of edges: tions. The representation learning process is guided by the
message propagation within the self-structure. We formalize
the procedure of structure-aware question-schema structure
• Table-Column Edges: For each column Cij ∈ Ci of table
linking as follows:
Ti , we add an edge E{Ti , Cij } ∈ RS connecting the table
node vTi to the column node vCij . This edge represents Gd′ = Agg(Gd , Gq ), (9)
the relationship between a table and its columns. Gq′ = Agg(Gq , Gd ), (10)
E(Ti , Cij ) = {vTi , vCij , "has"}. (6) where the structure-aware aggregation function Agg(.) is
employed to gather information from both the schema-graph
• Primary-Key Edges: If a column Cij ∈ Ci is the primary Gd and the query-graph Gq and transfer it to the adjacent
key column of table Ti , we add an edge E{Cij , Ti } ∈ Rd graph.
connecting the corresponding column nodes vCij and the Let {hqi }m
i=1 represent a set of node embeddings in the query
table vTi . The primary-key relations in the schema graph graph Gq and let {hkj }nj=1 denote a set of node embeddings
provide information about the structure and integrity con- in the subgraph Gk that extracted from the schema graph
straints of the database. Gd . In particular, we first employ global-average pooling on
the node embedding hqi of the query structure Gq to derive
E(Ti , Cij ) = {vTi , vCij , "primary_key"}. (7) the global query structure embedding hqg . Following this,
to encapsulate globally pertinent information, the key node
• Foreign-Key Edges: If a column Cij ∈ Ci of table Ti is a embedding hkj is updated subsequently:
foreign key referencing a primary key column Ckl ∈ Ck of
table Tk , we add an edge E{Cij , Ckl } ∈ Rd connecting 1 Xm q
hqg = h , (11)
the corresponding column nodes vCij and vCkl . This m i=1 i
edge represents the foreign key relationship between the αj = θ hqg T Wg hkj , (12)
columns. X
hkj = αl Wk hkl + αj Wk hkj (13)
l∈Nj
E(Cij , Ckl ) = {vCij , vCkl , "foreign_key"}. (8)
+(1 − αj )Wq hqg (14)
3.1.3. S TRUCTURE L INKING WITH D UAL G RAPH where Wg , Wq , Wk represent trainable parameters, and
E NCODING θ illustrates a sigmoid function. While αj denotes the rel-
evance score situated between the j-th key node and the
The syntax tree Tq obtained from parsing the user query Q
global query structure.
captures the syntactic structure of the query. It represents
the hierarchical relationships between query concepts and For each node a in the query structure Gq , it is necessary to
terms, which is crucial for understanding the intent behind find a corresponding matching node s in the database Gd .
the query. By incorporating the syntax tree into the query The proposed solution mainly consists of three steps. First,
graph Gq , we preserve the syntactic structure of the query a set of most relevant candidate nodes {s1 , s2 , . . . , sK } is
and its inherent meaning. The schema graph Gd represents identified through string matching in the set of tables and
4
Structure-Guided Large Language Models for Text-to-SQL Generation
columns V . Second, for each candidate node s, an enclos- first employ the query parsing described in Section 3.1.1
ing subgraph G(a, s) is constructed. As shown in Figure 1, to build the syntax tree to achieve a linguistic understand-
G(a, s) includes the query graph Gq , adjacent nodes of sk , ing of the natural language query and then adopt a node
and an edge connecting a and sk . Lastly, we adopt a struc- mapper to match nodes in the linguistic syntax tree to SQL
ture learning model RGAT(·) to learn the graph-level repre- operations (Kate, 2008). Following this, the original query
sentation of G( a, sk ) that captures the compatibility between can be divided into several subtasks according to the SQL
natural language concepts and database elements. operations distributed on the syntax tree.
5
Structure-Guided Large Language Models for Text-to-SQL Generation
Table 1: The Execution Accuracy of text-to-SQL models on S PIDER. The best and second-best results in each column are
highlighted in bold font and underlined. ✔ and ✘ represent that the case is applicable and not applicable, respectively.
6
Structure-Guided Large Language Models for Text-to-SQL Generation
BIRD (Li et al., 2023c). Spider, a cross-domain text-to-SQL based methods and 11 SOTA incontext-learning-based meth-
dataset, comprises 8659 instances in the training split and ods over two benchmark datasets. As shown in Table 1
1034 instances in the development split, spanning across and 2, SGU-SQL achieves superior performance across both
200 databases. Each instance comprises a natural language datasets, outperforming all baselines in terms of execution
question related to a specific database and its corresponding accuracy and exact match accuracy.
SQL query. For evaluation purposes, we utilize the Spider-
Obs.2. In-context learning-based method is better than the
dev development split since the test split has not been re-
methods of the other two categories. Among the three cate-
leased. On the other hand, BIRD (BIg Bench for large-scale
gories of methods, in-context learning-based methods con-
Database Grounded text-to-SQL Evaluation) is another pio-
sistently demonstrate superior performance. This suggests
neering cross-domain dataset that focuses on exploring the
that leveraging in-context learning mechanisms is crucial for
impact of extensive database contents on text-to-SQL pars-
enhancing the understanding and generation of SQL queries
ing. BIRD features over 12,751 unique question-SQL pairs,
from natural language inputs. Specifically, the in-context
encompassing 95 large databases with a total size of 33.4
learning-based methods, i.e., DIN-SQL and DAIL-SQL in
GB. It encompasses more than 37 professional domains.
our comparison set achieve higher accuracy rates and re-
Baselines To valid SGU-SQL, we compare it with several quire less computational overhead compared to fine-tuning
state-of-art baselines. Following the taxonomy in Sec- and structure-learning-based methods. Additionally, the
tion D, we divide baselines into three categories: (i) Fine- in-context learning-based methods exhibit better generaliza-
tuning: T5-base (Raffel et al., 2020), T5-large (Raffel tion across different datasets, indicating their robustness and
et al., 2020); (ii) structure-learning: RAT-SQL (Wang adaptability.
et al., 2019), RASAT (Qi et al., 2022), S2 SQL (Hui et al.,
2022) ,RESDSQL (Li et al., 2023a),GRAPHIX (Li et al., 4.3. Ablation Staudy: Q2
2023b); and (iii) incontext-learning: PaLM-2 (Anil et al.,
2023), CodeX (Chen et al., 2021), GPT-4 (OpenAI, 2023), The effect of prompting strategy In this part, we conduct
C3-GPT (Dong et al., 2023), DIN-SQL (Pourreza & Rafiei, comprehensive experiments to investigate the effectiveness
2023), DAIL-SQL (Gao et al., 2023), EPI-SQL (Liu & of our proposed prompting strategy. Specifically, we
Tan, 2024), SuperSQL (Li et al., 2024a), E-SQL (Cafer- compare the structure-based decomposing strategy used in
oğlu & Ulusoy, 2024), MAC-SQL (Wang et al., 2024), our SGU-SQL with other prompting strategies like CoT (Wei
PURPLE (Ren et al., 2024), CHESS (Talaei et al., 2024), et al., 2022) and few-shot prompting. As shown in Table 4
CHASE-SQL (Pourreza et al., 2024). and 8, we can have the following observations.
7
Structure-Guided Large Language Models for Text-to-SQL Generation
Table 2: The Execution Accuracy and Exact Match Accuracy of text-to-SQL models on S PIDER and B IRD. The best and
second-best results in each column are highlighted in bold font and underlined. NaN denotes that the result is not available.
Tables 4 and 8, applying COT on PaLM-2 even leads to the decomposing-based prompts. Specifically, we replace
a performance decrease of 1.08% compared to the naive GPT-4 used in SGU-SQL with other representative generative
few-shot prompting. This is attributed to the complex LLMs, including PaLM-2 (Anil et al., 2023), CodeX (Chen
syntax of SQL, and the intricate correspondence between et al., 2021), ChatGPT and GPT-4 (OpenAI, 2023) as alter-
query terms in user queries and database data units. natives. Specifically, we used the model ‘chat-bison-001’
Conversely, we formally define the meta-operations in provided by GoogleAI as the implementation of PaLM-2,
SQL and propose a decomposing strategy according to the and ‘ChatGPT-turbo’ and ‘gpt-4’ as the implementations
syntax tree to separate the query into subtasks. This boosts of ChatGPT and GPT-4, respectively. The text-to-SQL
the LLMs’ comprehension of linked queries to generate task is conducted under the few-shot setting with the query
accurate SQLs. from the development set of Spider as input. As shown in
Figure 4, we have the following observations.
The generalization ability of prompts
Obs.6. The performances of the original LLMs improved
To further verify the generalization ability of our proposed
significantly by integrating the prompt learned from our
prompting strategy, in this part, we conduct comprehensive
SGU-SQL. Specifically, PaLM-2 improved by 4%, CodeX
experiments to investigate whether SGU-SQL could enhance
by 3%, ChatGPT by 5%, and GPT-4 by almost 11%. The
other LLMs by substituting their original framework with
substantial performance gains indicate the robustness and
8
Structure-Guided Large Language Models for Text-to-SQL Generation
9
Structure-Guided Large Language Models for Text-to-SQL Generation
References Chen, S., Zhang, Q., Dong, J., Hua, W., Li, Q., and Huang,
X. Entity alignment with noisy annotations from large lan-
Achiam, J., Adler, S., Agarwal, S., Ahmad, L., Akkaya, I.,
guage models. arXiv preprint arXiv:2405.16806, 2024b.
Aleman, F. L., Almeida, D., Altenschmidt, J., Altman, S.,
Anadkat, S., et al. Gpt-4 technical report. arXiv preprint Chen, X., Lin, M., Schärli, N., and Zhou, D. Teaching
arXiv:2303.08774, 2023. large language models to self-debug. In International
Conference on Learning Representations (ICLR), 2024c.
Anil, R., Dai, A. M., Firat, O., Johnson, M., Lepikhin,
D., Passos, A., Shakeri, S., Taropa, E., Bailey, P., Chen, Choi, D., Shin, M. C., Kim, E., and Shin, D. R. Ryansql: Re-
Z., et al. Palm 2 technical report. arXiv preprint cursively applying sketch-based slot fillings for complex
arXiv:2305.10403, 2023. text-to-sql in cross-domain databases. Computational
Linguistics, 2021.
Bi, B., Liu, S., Mei, L., Wang, Y., Ji, P., and Cheng, X. De-
coding by contrasting knowledge: Enhancing llms’ confi- Devlin, J., Chang, M.-W., Lee, K., and Toutanova, K. BERT:
dence on edited facts. arXiv preprint arXiv:2405.11613, Pre-training of deep bidirectional transformers for lan-
2024. guage understanding. In North American Chapter of
the Association for Computational Linguistics: Human
Bi, B., Liu, S., Wang, Y., Xu, Y., Fang, J., Mei, L., and
Language Technologies (NAACL-HLT), 2019.
Cheng, X. Parameters vs. context: Fine-grained control
of knowledge reliance in language models. arXiv preprint Dong, J., Zhang, Q., Zhou, C., Chen, H., Zha, D., and
arXiv:2503.15888, 2025. Huang, X. Cost-efficient knowledge-based question an-
swering with large language models. arXiv preprint
Brown, T., Mann, B., Ryder, N., Subbiah, M., Kaplan, J. D.,
arXiv:2405.17337, 2024.
Dhariwal, P., Neelakantan, A., Shyam, P., Sastry, G.,
Askell, A., Agarwal, S., Herbert-Voss, A., Krueger, G., Dong, X., Zhang, C., Ge, Y., Mao, Y., Gao, Y., lu Chen, Lin,
Henighan, T., Child, R., Ramesh, A., Ziegler, D., Wu, J., J., and Lou, D. C3: Zero-shot text-to-sql with chatgpt,
Winter, C., Hesse, C., Chen, M., Sigler, E., Litwin, M., 2023.
Gray, S., Chess, B., Clark, J., Berner, C., McCandlish,
S., Radford, A., Sutskever, I., and Amodei, D. Language Dou, L., Gao, Y., Liu, X., Pan, M., Wang, D., Che, W.,
models are few-shot learners. In Advances in Neural Zhan, D., Kan, M.-Y., and Lou, J.-G. Towards knowledge-
Information Processing Systems (NeurIPS), 2020. intensive text-to-SQL semantic parsing with formulaic
knowledge. In Empirical Methods in Natural Language
Busbridge, D., Sherburn, D., Cavallo, P., and Hammerla, Processing (EMNLP), 2022.
N. Y. Relational graph attention networks. arXiv preprint
arXiv:1904.05811, 2019. Fang, J., Wang, Y., Wang, R., Yao, Z., Wang, K., Zhang,
A., Wang, X., and Chua, T.-S. Safemlrm: Demystifying
Caferoğlu, H. A. and Ulusoy, Ö. E-sql: Direct schema safety in multi-modal large reasoning models. arXiv
linking via question enrichment in text-to-sql. arXiv preprint arXiv:2504.08813, 2025.
preprint arXiv:2409.16751, 2024.
Gao, D., Wang, H., Li, Y., Sun, X., Qian, Y., Ding,
Cao, R., Chen, L., Chen, Z., Zhao, Y., Zhu, S., and Yu, B., and Zhou, J. Text-to-sql empowered by large lan-
K. Lgesql: line graph enhanced text-to-sql model with guage models: A benchmark evaluation. arXiv preprint
mixed local and non-local relations. arXiv preprint arXiv:2308.15363, 2023.
arXiv:2106.01093, 2021.
Gao, D., Wang, H., Li, Y., Sun, X., Qian, Y., Ding, B., and
Chang, S. and Fosler-Lussier, E. How to prompt LLMs for Zhou, J. Text-to-sql empowered by large language mod-
text-to-SQL: A study in zero-shot, single-domain, and els: A benchmark evaluation. In International Conference
cross-domain settings. In NeurIPS 2023 Second Table on Very Large Data Bases (VLDB), 2024.
Representation Learning Workshop (NeurIPS), 2023.
Guo, C., Tian, Z., Tang, J., Wang, P., Wen, Z., Yang, K., and
Chen, M., Tworek, J., Jun, H., Yuan, Q., Pinto, H. P. d. O., Wang, T. A case-based reasoning framework for adaptive
Kaplan, J., Edwards, H., Burda, Y., Joseph, N., Brockman, prompting in cross-domain text-to-sql. arXiv preprint
G., et al. Evaluating large language models trained on arXiv:2304.13301, 2023.
code. arXiv preprint arXiv:2107.03374, 2021.
Guo, J., Zhan, Z., Gao, Y., Xiao, Y., Lou, J.-G., Liu, T., and
Chen, S., Zhang, Q., Dong, J., Hua, W., Cao, J., and Huang, Zhang, D. Towards complex text-to-sql in cross-domain
X. Neuro-symbolic entity alignment via variational infer- database with intermediate representation. arXiv preprint
ence. arXiv preprint arXiv:2410.04153, 2024a. arXiv:1905.08205, 2019.
10
Structure-Guided Large Language Models for Text-to-SQL Generation
Hochreiter, S. and Schmidhuber, J. Long short-term memory. a database interface? a big bench for large-scale database
Neural Computation, 1997. grounded text-to-sqls. arXiv preprint arXiv:2305.03111,
2023c.
Hong, Z., Yuan, Z., Chen, H., Zhang, Q., Huang, F., and
Huang, X. Knowledge-to-sql: Enhancing sql generation Liu, A., Hu, X., Wen, L., and Yu, P. S. A comprehensive
with data expert llm. arXiv preprint arXiv:2402.11517, evaluation of chatgpt’s zero-shot text-to-sql capability.
2024a. arXiv preprint arXiv:2303.13547, 2023.
Hong, Z., Yuan, Z., Chen, H., Zhang, Q., Huang, F., and Liu, J., Shen, D., Zhang, Y., Dolan, B., Carin, L., and Chen,
Huang, X. Knowledge-to-sql: Enhancing sql generation W. What makes good in-context examples for gpt-3?
with data expert llm. arXiv preprint arXiv:2402.11517, arXiv preprint arXiv:2101.06804, 2021.
2024b.
Liu, X. and Tan, Z. Epi-sql: Enhancing text-to-sql trans-
Hong, Z., Yuan, Z., Zhang, Q., Chen, H., Dong, J., Huang, lation with error-prevention instructions. arXiv preprint
F., and Huang, X. Next-generation database inter- arXiv:2404.14453, 2024.
faces: A survey of llm-based text-to-sql. arXiv preprint
arXiv:2406.08426, 2024c. Mahmud, T., Hasan, K. A., Ahmed, M., and Chak, T. H. C.
A rule based approach for nlp based query processing. In
Hui, B., Geng, R., Wang, L., Qin, B., Li, B., Sun, J., and Li, International Conference on Electrical Information and
Y. S2 sql: Injecting syntax to question-schema interaction Communication Technologies (EICT), 2015.
graph encoder for text-to-sql parsers, 2022.
Müller, M. and Sennrich, R. Understanding the proper-
Kate, R. Transforming meaning representation grammars ties of minimum Bayes risk decoding in neural machine
to improve semantic parsing. In CoNLL 2008: Proceed- translation. In Association for Computational Linguistics
ings of the Twelfth Conference on Computational Natural and International Joint Conference on Natural Language
Language Learning, pp. 33–40, 2008. Processing (ACL-IJCNLP), 2021.
Lei, F., Chen, J., Ye, Y., Cao, R., Shin, D., Su, H., Suo, Nan, L., Zhao, Y., Zou, W., Ri, N., Tae, J., Zhang, E.,
Z., Gao, H., Hu, W., Yin, P., et al. Spider 2.0: Evaluat- Cohan, A., and Radev, D. Enhancing few-shot text-to-sql
ing language models on real-world enterprise text-to-sql capabilities of large language models: A study on prompt
workflows. arXiv preprint arXiv:2411.07763, 2024. design strategies. arXiv preprint arXiv:2305.12586, 2023.
Li, B., Luo, Y., Chai, C., Li, G., and Tang, N. The dawn Ni, A., Iyer, S., Radev, D., Stoyanov, V., Yih, W.-t., Wang,
of natural language to sql: Are we fully ready? arXiv S. I., and Lin, X. V. Lever: Learning to verify language-
preprint arXiv:2406.01265, 2024a. to-code generation with execution. In International Con-
ference on Machine Learning (ICML), 2023.
Li, F. and Jagadish, H. V. Constructing an interactive natural
language interface for relational databases. In Interna- OpenAI. Gpt-4 technical report, 2023.
tional Conference on Very Large Data Bases (VLDB),
2014. Pourreza, M. and Rafiei, D. DIN-SQL: Decomposed
in-context learning of text-to-SQL with self-correction.
Li, H., Zhang, J., Li, C., and Chen, H. Resdsql: Decoupling In Advances in Neural Information Processing Systems
schema linking and skeleton parsing for text-to-sql. In (NeurIPS), 2023.
Proceedings of the AAAI Conference on Artificial Intelli-
gence, volume 37, pp. 13067–13075, 2023a. Pourreza, M., Li, H., Sun, R., Chung, Y., Talaei, S., Kakkar,
G. T., Gan, Y., Saberi, A., Ozcan, F., and Arik, S. O.
Li, H., Zhang, J., Liu, H., Fan, J., Zhang, X., Zhu, J., Wei, Chase-sql: Multi-path reasoning and preference opti-
R., Pan, H., Li, C., and Chen, H. Codes: Towards building mized candidate selection in text-to-sql. arXiv preprint
open-source language models for text-to-sql. In Confer- arXiv:2410.01943, 2024.
ence on Management of Data (SIGMOD), 2024b.
Qi, J., Tang, J., He, Z., Wan, X., Cheng, Y., Zhou, C., Wang,
Li, J., Hui, B., Cheng, R., Qin, B., Ma, C., Huo, N., Huang, X., Zhang, Q., and Lin, Z. Rasat: Integrating relational
F., Du, W., Si, L., and Li, Y. Graphix-t5: Mixing pre- structures into pretrained seq2seq model for text-to-sql.
trained transformers with graph-aware layers for text-to- arXiv preprint arXiv:2205.06983, 2022.
sql parsing. arXiv preprint arXiv:2301.07507, 2023b.
Radford, A., Narasimhan, K., Salimans, T., Sutskever, I.,
Li, J., Hui, B., Qu, G., Li, B., Yang, J., Li, B., Wang, B., et al. Improving language understanding by generative
Qin, B., Cao, R., Geng, R., et al. Can llm already serve as pre-training. OpenAI blog, 2018.
11
Structure-Guided Large Language Models for Text-to-SQL Generation
Raffel, C., Shazeer, N., Roberts, A., Lee, K., Narang, S., Wang, C., Liu, Y., Li, B., Zhang, D., Li, Z., and Fang,
Matena, M., Zhou, Y., Li, W., and Liu, P. J. Exploring J. Safety in large reasoning models: A survey. arXiv
the limits of transfer learning with a unified text-to-text preprint arXiv:2504.17704, 2025.
transformer. The Journal of Machine Learning Research,
21(1):5485–5551, 2020. Wei, J., Wang, X., Schuurmans, D., Bosma, M., Xia, F.,
Chi, E., Le, Q. V., Zhou, D., et al. Chain-of-thought
Rajkumar, N., Li, R., and Bahdanau, D. Evaluating the prompting elicits reasoning in large language models.
text-to-sql capabilities of large language models. arXiv Advances in Neural Information Processing Systems, 35:
preprint arXiv:2204.00498, 2022. 24824–24837, 2022.
Ren, T., Fan, Y., He, Z., Huang, R., Dai, J., Huang, C., Jing, Xu, F., Wu, Z., Sun, Q., Ren, S., Yuan, F., Yuan, S., Lin, Q.,
Y., Zhang, K., Yang, Y., and Wang, X. S. Purple: Making Qiao, Y., and Liu, J. Symbol-llm: Towards foundational
a large language model a better sql writer. arXiv preprint symbol-centric interface for large language models. arXiv
arXiv:2403.20014, 2024. preprint arXiv:2311.09278, 2024.
Roziere, B., Gehring, J., Gloeckle, F., Sootla, S., Gat, I., Yang, C., Wang, X., Jiang, J., Zhang, Q., and Huang, X.
Tan, X. E., Adi, Y., Liu, J., Remez, T., Rapin, J., et al. Evaluating world models with llm for decision making.
Code llama: Open foundation models for code. arXiv arXiv preprint arXiv:2411.08794, 2024.
preprint arXiv:2308.12950, 2023.
Yin, P., Neubig, G., Yih, W.-t., and Riedel, S. Tabert: Pre-
Scholak, T., Schucher, N., and Bahdanau, D. Picard: Parsing training for joint understanding of textual and tabular data.
incrementally for constrained auto-regressive decoding arXiv preprint arXiv:2005.08314, 2020.
from language models. arXiv preprint arXiv:2109.05093,
2021. Yu, T., Zhang, R., Yang, K., Yasunaga, M., Wang, D., Li,
Z., Ma, J., Li, I., Yao, Q., Roman, S., Zhang, Z., and
Shi, F., Fried, D., Ghazvininejad, M., Zettlemoyer, L., and Radev, D. Spider: A large-scale human-labeled dataset
Wang, S. I. Natural language to code translation with for complex and cross-domain semantic parsing and text-
execution. In Empirical Methods in Natural Language to-SQL task. In Empirical Methods in Natural Language
Processing (EMNLP), 2022. Processing (EMNLP), 2018.
Sun, R., Arik, S. O., Nakhost, H., Dai, H., Sinha, R., Yu, T., Zhang, R., Yang, K., Yasunaga, M., Wang, D., Li,
Yin, P., and Pfister, T. Sql-palm: Improved large lan- Z., Ma, J., Li, I., Yao, Q., Roman, S., Zhang, Z., and
guage modeladaptation for text-to-sql. arXiv preprint Radev, D. Spider: A large-scale human-labeled dataset
arXiv:2306.00739, 2023. for complex and cross-domain semantic parsing and text-
Talaei, S., Pourreza, M., Chang, Y.-C., Mirhoseini, A., and to-sql task, 2019.
Saberi, A. Chess: Contextual harnessing for efficient sql
Yu, T., Wu, C.-S., Lin, X. V., bailin wang, Tan, Y. C., Yang,
synthesis. arXiv preprint arXiv:2405.16755, 2024.
X., Radev, D., richard socher, and Xiong, C. Grappa:
Trummer, I. Codexdb: Synthesizing code for query pro- Grammar-augmented pre-training for table semantic pars-
cessing from natural language instructions using gpt-3 ing. In International Conference on Learning Represen-
codex. Proceedings of the VLDB Endowment, 15(11): tations (ICLR), 2021.
2921–2928, 2022.
Yuan, Z., Chen, H., Hong, Z., Zhang, Q., Huang, F., and
Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, Huang, X. Knapsack optimization-based schema link-
L., Gomez, A. N., Kaiser, Ł., and Polosukhin, I. Atten- ing for llm-based text-to-sql generation. arXiv preprint
tion is all you need. In Advances in Neural Information arXiv:2502.12911, 2025.
Processing Systems (NeurIPS), 2017.
Zhang, Q., Dong, J., Chen, H., Zha, D., Yu, Z., and Huang,
Wang, B., Shin, R., Liu, X., Polozov, O., and Richardson, X. Knowgpt: Knowledge graph based prompting for
M. Rat-sql: Relation-aware schema encoding and linking large language models. Advances in Neural Information
for text-to-sql parsers. arXiv preprint arXiv:1911.04942, Processing Systems, 37:6052–6080, 2024.
2019.
Zhang, Q., Chen, S., Bei, Y., Yuan, Z., Zhou, H., Hong, Z.,
Wang, B., Ren, C., Yang, J., Liang, X., Bai, J., Chai, L., Dong, J., Chen, H., Chang, Y., and Huang, X. A survey
Yan, Z., Zhang, Q.-W., Yin, D., Sun, X., et al. Mac-sql: A of graph retrieval-augmented generation for customized
multi-agent collaborative framework for text-to-sql. arXiv large language models. arXiv preprint arXiv:2501.13958,
preprint arXiv:2312.11242, 2024. 2025.
12
Structure-Guided Large Language Models for Text-to-SQL Generation
Zhou, H., Zhou, S., Chen, H., Liu, N., Yang, F., and Huang,
X. Enhancing explainable rating prediction through anno-
tated macro concepts. In Proceedings of the 62nd Annual
Meeting of the Association for Computational Linguistics
(Volume 1: Long Papers), pp. 11736–11748, 2024.
Zhuang, A., Zhang, G., Zheng, T., Du, X., Wang, J., Ren,
W., Huang, S. W., Fu, J., Yue, X., and Chen, W. Structlm:
Towards building generalist models for structured knowl-
edge grounding. arXiv preprint arXiv:2402.16671, 2024.
13
Structure-Guided Large Language Models for Text-to-SQL Generation
A. Ablation Study
In this section, we have conducted detailed experiments to validate the effectiveness of each component in SGU-SQL.
Variant Full Model w/o query graph w/o database graph w/o structure linking w/o decomposition
SPIDER-dev 87.95 84.50 (-3.45) 85.81 (-2.14) 82.62 (-5.33) 82.35 (-5.60)
BIRD-dev 61.80 58.93 (-2.87) 58.26 (-3.54) 55.31 (-6.49) 53.78 (-8.02)
As shown in Tables 3 and 4, (i) the ablation of our decomposition strategy leads to the most significant performance decrease
(-5.60% on Spider-dev, -8.02% on BIRD-dev). These results validate our approach of breaking down complex queries
into manageable components while preserving structural relationships, especially beneficial for real-world applications
involving complex dabase structure and intricate query patterns. (ii) Our SGU-SQL achieves 87.95% execution accuracy
on SPIDER-dev, outperforming all these methods. The key distinction of our approach is that it dynamically decomposes
queries based on their syntax structure, rather than either using fixed decomposition patterns (like DIN-SQL) or purely
relying on LLM’s black-box understanding (like ACT-SQL, MAC-SQL). This syntax-aware decomposition strategy proves
more effective for handling complex SQL generation tasks.
14
Structure-Guided Large Language Models for Text-to-SQL Generation
iteratively refine generated queries. In contrast, our model generates SQL queries in a single pass without utilizing any
execution feedback.
B. Model Analysis
B.1. Performance on more Challenging Dataset
To further verify the effectiveness of our model, we conduct additional experiments on more challenging datasets, like
Spider 2.0-Snow and Spider 2.0-Lite (Lei et al., 2024). As shown in Table 6, while the performances are relatively low
across all models, SGU-SQL consistently demonstrates better capability in handling complex SQL generation tasks in both
single and multi-database scenarios.
15
Structure-Guided Large Language Models for Text-to-SQL Generation
schema-linking and join statement components where traditional models often falter. Errors in the schema-linking segment
decreased by around 38%, primarily attributed to the utilization of Precise Query Matching, wherein graph neural networks
were employed to learn and match the database schema. This underscores the efficacy of Structure Linking. In the sections
prone to errors, such as Group-by and Join, our errors decreased by 35%, indicating that our syntax tree decomposing
enables the model to more accurately utilize corresponding SQL Meta-operations to mine the intentions behind queries, thus
further enhancing the accuracy in identifying the targeted tables or columns for manipulation.
To further analyze the reasons for errors in the baseline model, we conducted a comprehensive case study by comparing the
results of the baseline model with those of our model, as shown in Figure 3.
Subtask Decomposing LLMs often do not adequately break down the task into its essential steps for reasoning. For
example, in Case 1, the primary subtask of linking flight data to specific cities was ignored. The question did not adequately
break down the task into its essential components without further guidance from LLMs. In Case 3, the query did not
decompose the task into two separate subtasks to identify semesters with Masters and Bachelors enrollments independently
which also leads to wrong returned answers.
Intention Understanding LLMs sometimes misunderstand the core intention of the question. In Case 2, LLMs fail to
identify the intention that the question is trying to find all countries where English is spoken, regardless of its official status
which leads to errors. It concentrated on the official language status, which did not align with the broader objective of
considering English-speaking countries in general. In Case 1, the query was centered around airport codes (SourceAirport),
misinterpreting the intention to identify the busiest city, not just the airport. In Case 3, LLM misinterprets the intention of
finding how many likes Kyle has received. It erroneously assumes the task is to count how many likes Kyle has given, not
received.
Data Schema Linking Since LLMs get data schema information with plain text as inputs, it might be challenging to
reason the right linking strategy to solve the problem correctly. It needs to understand the referenced tables and columns in
the question which are often being mentioned in an inexplicitly way, then matching with the database schema. In contrast,
our tailored GNN model can handle this situation well. In Case 1, the initial query failed to incorporate the airport’s table,
which was essential for linking airport codes to their respective cities. In Case 3, the query did not effectively link degree
program types (Masters, Bachelors) to semesters in databases in a way that would allow for the inclusive identification of
valid semesters. There was also a misalignment in linking: student_id from the Likes table was incorrectly associated
with the id in Highschooler table. It should link liked_id from Likes to id in Highschooler to align with the task’s
objective.
C. Preliminaries
C.1. Structure Learning for Text-to-SQL
Definition 1. Structure Learning for Text-to-SQL: Given a natural language query D and a database schema Q, the task
of graph learning for Text-to-SQL aims to generate a graph-based representation G that captures the structural and semantic
relationships between the query and the schema, and to learn a mapping function f : Gq → Gd , where Gq is the structural
user queries, and Gd is the corresponding database contents linked to the query Gq .
Let G = (V, E) denote the graph representation, where V is the set of nodes and E is the set of edges. The nodes v ∈ V
represent the entities and components in the query and schema, such as tables, columns, and query tokens. The edges e ∈ E
represent the relationships and dependencies between the nodes. The graph learning task involves two main components,
Table 6: Execution accuracy for baseline methods on Spider 2.0-Snow and Spider 2.0-Lite.
16
Structure-Guided Large Language Models for Text-to-SQL Generation
NL Query: What is the code of airport that has the highest number of flights?
/* Given the following database schema: */
CREATE TABLE ’flights’ (
Airline INTEGER,
Prompts from
...
Baseline Model
/* Answer the following: What is the code of airport*/;
that has the highest number of flights? */;
Let’s think step by step.
Results from SELECT SourceAirport, COUNT(*) AS NumberOfFlights
Baseline Model’s FROM flights GROUP BY SourceAirport
Prompt ORDER BY NumberOfFlights DESC LIMIT 1;
SELECT [Link]
FROM AIRPORTS AS T1
JOIN FLIGHTS AS T2 ON [Link] = [Link]
Gold SQL
OR [Link] = [Link]
GROUP BY [Link]
ORDER BY count(*) DESC LIMIT 1;
Figure 3: NL query from Spider and the corresponding results from different prompting approaches
17
Structure-Guided Large Language Models for Text-to-SQL Generation
where Construct(·) is a method that maps the query and schema to the graph representation.
h(l+1)
v = GNN(h(l) (l)
v , {hu : u ∈ N (v)}), (20)
(l)
where hv is the representation of node v at layer l, N (v) is the set of neighboring nodes of v, and GNN(·) is the graph
neural network function that updates the node representations based on their neighbors. The learned graph representations
are then used to generate the corresponding SQL query S by applying a decoding function f to the graph:
S = f (G). (21)
The objective of graph learning for Text-to-SQL is to optimize the parameters of the graph construction and representation
learning components, as well as the decoding function, to generate accurate and executable SQL queries from natural
language queries and database schemas.
The objective of LLM-based text-to-SQL generation is to learn the optimal parameters or prompts θ∗ that minimize the
difference between the generated SQL query M(Q, D, θ) and the ground truth SQL query S:
where L is a loss function that measures the discrepancy between generated and ground truth SQLs.
18
Structure-Guided Large Language Models for Text-to-SQL Generation
D. Related Work
Text-to-SQL has witnessed significant evolution over the past few years (Hong et al., 2024c). Early researchers focused
on well-designed rules, which were later superseded by deep learning-based techniques. More recently, the integration of
pre-trained language models (PLMs) and large language models (LLMs) (Wang et al., 2025; Fang et al., 2025) has further
advanced state-of-the-art text-to-SQL generation. This section traces the developmental trajectory of text-to-SQL methods,
highlighting the key milestones and innovations that have shaped the field.
Table 8: Ablation Study: Performance comparison of different prompting strategies on the development set of Spider.
19
Structure-Guided Large Language Models for Text-to-SQL Generation
coding tasks, including text-to-SQL. This process enables models to master programming language syntax and database
schema intricacies (Raffel et al., 2020; Roziere et al., 2023). Through training on tailored datasets of annotated SQL queries,
LLMs acquire the syntax and structure necessary for generating compliant SQL code (Trummer, 2022; Sun et al., 2023).
Furthermore, PICARD (Scholak et al., 2021) introduced a decoding mechanism for LLMs that ensures the generation of
valid sequences by discarding inadmissible tokens at each step, employing incremental parsing to guarantee the validity
of SQL queries produced by autoregressive language models. More recently, data-augmented fine-tuning techniques have
emerged as a promising approach to improve text-to-SQL generation models. By focusing on enhancing the quality and
diversity of the training data during supervised fine-tuning, these methods enable models to better capture the complexities
of translating natural language queries into SQL statements. For example, Symbol-LLM (Xu et al., 2024) proposes a
two-stage approach, consisting of an injection stage and an infusion stage, for data-augmented instruction tuning. This
method effectively incorporates additional data to improve the LLM’s ability to follow instructions. Similarly, CodeS (Li
et al., 2024b) leverages ChatGPT to generate bi-directional training data, augmenting the model’s training dataset and
enhancing its code generation capabilities. Additionally, StructLM (Zhuang et al., 2024) introduces a training paradigm
that involves multiple structured knowledge tasks, aiming to improve the model’s overall performance across a wide range
of applications. These approaches demonstrate the potential of data augmentation and multi-task learning in boosting the
performance of LLMs.
20
Structure-Guided Large Language Models for Text-to-SQL Generation
E. Future Work
Discussing potential extensions is crucial for the research community. Following your suggestion, we have identified several
promising future research directions from the following there perspectives.
21