January 16, 2026
Application of LLMs to optimize SQL queries in enterprise environments
Author: Luiza Batista Laquini — Advisor: Dora Yovana Barrios Leal
Summary prepared by the ResumeAI tool, an artificial intelligence solution developed by Instituto Pecege focused on synthesis and writing.
This work develops and evaluates an application based on language models (LLMs) to convert natural language into optimized SQL queries, aiming to streamline data access in business environments, specifically in e-commerce. The research seeks to improve query formulation efficiency, increase accessibility for non-technical users, and advance natural language processing techniques applied to data management. Digitization, intensified by the pandemic, has generated an exponential increase in data volume (Garg et al., 2021), posing the challenge of transforming raw information into knowledge for strategic decisions. The e-commerce sector exemplifies this expansion, with Brazil registering a 16% growth in online sales in 2024, the largest globally (Atlântico, 2024). Each transaction generates data about the purchase process and consumer profile, which must be managed to comply with requirements such as LGPD (Brasil, 2018) and optimize operations like customer service and inventory management (Data Storage, 2023).
Extracting value from data relies on efficient queries in relational databases, where SQL is the standard. However, crafting optimized SQL queries is a challenge for business users without technical expertise, creating a barrier that limits autonomy in gaining insights. It is imperative to develop solutions that simplify data interaction. The emergence of Large Language Models (LLMs) presents an opportunity to overcome this barrier, acting as a bridge between human and machine language. LLMs are AI models trained on massive volumes of textual data, capable of understanding and generating natural language with high sophistication (IBM, 2023). Utilizing architectures like transformers, these models learn linguistic and contextual patterns, enabling them to perform complex Natural Language Processing (NLP) tasks.
Recent studies demonstrate the potential of LLMs to generate SQL from natural language. Hong et al. (2025) show that as these models scale up, they outperform traditional rule-based approaches, being effective in resolving ambiguities and generating complex queries. Additionally, Tan et al. (2025) indicate that LLMs can optimize queries, minimizing redundancies. The authors developed LLM-QO, an LLM-based query optimizer that generated high-quality execution plans, outperforming traditional optimizers. The ability to understand context makes LLMs valuable tools for query optimization in enterprise databases.
The relevance of the work lies in making data access more intuitive and efficient, integrating technology and decision-making. By developing a prototype that translates natural language questions into SQL, the research democratizes data access, allowing professionals from various fields to extract information without technical intermediaries. The empirical validation of the solution in an e-commerce environment, with real data and comparison of different LLMs, provides a basis for evaluating the technology’s feasibility. The proposal aligns with the trend of next-generation interfaces for databases, which seek to simplify human-computer interaction (Bao et al., 2023). The developed prototype validates the approach and offers a reproducible and scalable model for different business contexts.
The expected impact is multifaceted, including increased productivity and improved analytical intelligence. By reducing the technical barrier, the solution empowers business users to perform their own analyses, accelerating insight discovery. The automation of SQL generation minimizes the risk of human errors, resulting in more reliable analyses. The comparison between reasoning and intelligence models offers a contribution to the field, elucidating the trade-offs between accuracy, speed, and cost, crucial information for the implementation of LLMs in production. This study contributes to the advancement of NLP applications in data management, demonstrating how generative AI can transform companies’ interaction with their information assets.
The methodology began with the selection of a representative database. The experiment used an e-commerce dataset from Olist Store, available on Kaggle (Kaggle, 2022), containing 100,000 anonymized orders in Brazil between 2016 and 2018. The dataset, with eight interrelated tables, covers dimensions such as order status, price, payment, shipping, customer location, product attributes, and reviews. The complexity of the schema represents a challenging scenario for query generation, making it ideal for testing the ability of LLMs to understand complex relationships.
Before implementation, an exploratory analysis and data treatment were performed with Python and libraries such as ydata_profiling, pandas, numpy, and matplotlib. This step was crucial for understanding the data structure and identifying inconsistencies. Corrections were applied, such as proper column typing (strings to datetime, text to numbers), standardization of date formats, and handling of null values. Referential integrity was assessed to ensure the correspondence between foreign and primary keys, eliminating inconsistencies that would compromise join operations and temporal analyses. These changes ensured the quality of the results.
The selection of language models considered the infeasibility of hosting proprietary LLMs. The OpenAI platform was chosen for its high-performance models and robust API. Four models were tested, divided into two categories: reasoning and intelligence. Reasoning models, such as 4-mini and 3-mini, are trained with reinforcement learning to execute internal thought chains, excelling in complex problems (Platform OpenAI, 2025). Intelligence models, such as GPT-4.1 and GPT-4.1-mini, are optimized for contextual understanding and rapid content generation, ideal for tasks like text summarization (Platform OpenAI, 2025). The selection, in May 2025, considered capacity, availability, and cost-effectiveness.
A prototype was developed with a Front-end interface in Streamlit and a Back-end API in Flask. The API orchestrates message interpretation, data querying, and response generation. The logic was modularized: an LLM acts as a router, identifying whether the question is a data request or an informal conversation. Casual interactions follow a simplified route to save resources. Data requests follow a two-step main route: an LLM transforms the question into SQL and, after query execution, another LLM interprets the result and generates a natural language response. For evaluation, 21 questions of varying complexity were formulated, collecting the SQL query, processing time, and final answer. Assertiveness was evaluated on a scale from 0 (major error) to 2 (correct answer). A consistency analysis was also performed on the best-performing model.
The prototype resulted in a functional application with login and chat. The API demonstrated robustness, and the modular architecture proved efficient in resource optimization. The comparative evaluation revealed significant performance differences. The o4-mini (reasoning) model achieved 100% total accuracy (42 points), demonstrating superior capability. The o3-mini (reasoning) model obtained 90.48% accuracy (39 points), with 19 total correct answers, one with reservations, and one error. In contrast, the intelligence models had inferior performance. GPT-4.1 achieved 76.19% accuracy (33 points), with 16 correct answers and 4 errors, while GPT-4.1-mini registered 61.9% (28 points), with 13 correct answers and 6 errors.
The results indicate the superiority of reasoning models in assertiveness for text-to-SQL conversion, a critical factor in business contexts. Granular analysis identified questions 10 and 12 as a challenge for all models except o4-mini, suggesting that certain complexities require advanced reasoning capabilities. A discrepancy was observed in question 9, where GPT-4.1-mini outperformed GPT-4.1, indicating that performance can be influenced by training nuances of each model.
Regarding response time, the intelligence models were, on average, almost three times faster and with less variability than the reasoning ones. The response time curves showed that models of the same category follow similar patterns, suggesting that temporal differences are more linked to the category’s architecture. Although speed is desirable, a difference of a few seconds is acceptable in data analysis, especially when compensated by a gain in precision. The total processing time of any model is drastically lower than that of a human analyst, representing an advance in productivity.
The consistency evaluation in o4-mini reinforced its robustness. In 90.47% of cases (19 out of 21), the model maintained total consistency between the original question and its variations. The two inconsistencies (questions 7 and 20) were attributed to ambiguities in the user’s formulation, such as the omission of a filter. This shows that the clarity of the user’s prompt is still important. The high overall consistency rate validates the model’s viability for production use.
The contextualization with related works reinforces the innovation of the approach. Unlike CodexDB (Trummer, 2022), which explores code synthesis, this prototype stands out for its route modularity to optimize costs. Compared to EcomGPT (Xu et al., 2023), which focuses on fine-tuning, this study demonstrates that general-purpose reasoning models, such as o4-mini, achieve high assertiveness without specific training, suggesting prompt engineering as a viable alternative. The research aligns with the conclusions of Bao et al. (2023), who highlight the need for robust models for the growing complexity of queries in real-world environments.
The comparative analysis offers practical insights. Reasoning models, despite being slower, break down complex problems and interpret relationships between tables with greater precision. This ability to “think before responding” (Platform OpenAI, 2025) explains their higher accuracy rate. The speed of intelligence models makes them attractive for real-time applications, such as chatbots, where a small margin of error is tolerable (Zhou, Fang, & Liu, 2023). For data analysis that informs business decisions, accuracy is non-negotiable, making reasoning models the more prudent choice.
The API’s modularity, with separate routing and steps for SQL generation and result interpretation, is a scalable architecture. This separation optimizes token consumption and costs, allowing granular control over the process. The ability to efficiently handle informal conversations avoids wasting computational resources, improving overall efficiency.
The research also highlights the importance of data quality. The cleaning step was fundamental to ensure that LLMs operated on a reliable basis. Inconsistencies in the data could lead the models to generate incorrect queries. The successful implementation of a natural language interface depends on both the LLM’s capability and the governance of the underlying data. The combination of a powerful LLM with a well-structured database is key to conversational data analysis.
In conclusion, the study demonstrated the prototype’s capability to transform natural language questions into precise SQL queries on a complex database. The evaluation revealed that the o4-mini (reasoning) model showed superior performance, with 100% accuracy, validating its suitability for high-precision scenarios. Although the intelligence models are faster, their lower accuracy makes them less suitable for business intelligence. The prototype’s modular architecture proved effective, favoring reproducibility, scalability, and cost optimization. The high consistency of o4-mini reinforces its viability for continuous use.
The work contributes with an empirical validation of the application of LLMs to democratize access to data, with the potential to impact the productivity and analytical intelligence of organizations. Although the results are promising, future research can expand the evaluation with more questions and use scenarios. It is concluded that the objective was achieved: it was demonstrated that the application of LLMs, especially the o4-mini model, is a viable and effective solution for transforming natural language questions into precise and optimized SQL queries in an e-commerce environment.
References:
Atlântico. 2024. Latin America Digital Transformation Report 2024. Available at: https://www. atlantico. vc/latin-america-digital-transformation-report-2024. Accessed on March 18, 2025.
Bao, S., Liu, Y., Li, B., Zhang, Z., Wang, Q., & Sun, M. (2023). Next‑Generation Database Interfaces: A Survey of LLM‑based Text‑to‑SQL. arXiv. Available at: https://arxiv. org/abs/2308.08709. Accessed on: July 20, 2025.
BRASIL. 2018. Law nº 13.709, of August 14, 2018. General Data Protection Law (LGPD). Official Gazette of the Union, Brasília, August 15, 2018. Section 1, p. 1. Accessed on: March 18, 2025.
Data Storage. 2023. Data Storage for E-commerce: Supporting Online Sales Growth. Available at: https://blog. datastorage. com. br/post/armazenamento-de-dados-para-e-commerce-suportando-o-crescimento-das-vendas-online. Accessed on: March 18, 2025.
Garg, A., Popli, R., & Sarao, B. S. (2021). Growth of Digitization and its Impact on Big Data Analytics. IOP Conference Series: Materials Science and Engineering, Volume 1022, 1st International Conference on Computational Research and Data Analytics (ICCRDA 2020) October 24, 2020, Rajpura, India. Available at: https://iopscience. iop. org/article/10.1088/1757-899X/1022/1/012083/pdf. Accessed on: March 18, 2025.
Hong, Z., Yuan, Z., Zhang, Q., Chen, H., Dong, J., Huang, F., & Huang, X. (2025). Next-Generation Database Interfaces: A Survey of LLM-based Text-to-SQL. https://doi. org/10.48550/arXiv.2406.08426
IBM. 2023. What are large language models (LLMs)? Available at: https://www. ibm. com/think/topics/large-language-models. Accessed on: March 18, 2025.
Kaggle. 2022. Brazilian E-Commerce Public Dataset by Olist. Available at: https://www. kaggle. com/datasets/olistbr/brazilian-ecommerce. Accessed on: Mar. 14, 2025.
Platform OpenAI. 2025. Core Concepts – Reasoning Models Guide. Available at: https://platform. openai. com/docs/guides/reasoning? api-mode=responses
Platform OpenAI. 2025. Get started – Models Guide. Available at: https://platform. openai. com/docs/models
Sala, L., Sullutrone, G., & Bergamaschi, S. (2024). Text-to-SQL with Large Language Models: Exploring the Promise and Pitfalls. SEBD 2024: 32nd Symposium on Advanced Database Systems, 2024, Villasimius, Sardinia, Italy. Available at: https://ceur-ws. org/Vol-3741/paper65. pdf
Tan, J., Zhao, K., Li, R., Yu, J. X., Piao, C., Cheng, H., Meng, H., Zhao, D., & Rong, Y. (2025). Can Large Language Models Be Query Optimizer for Relational Databases?. https://doi. org/10.48550/arXiv.2502.05562
Trummer, I. (2022). CodexDB: Generating SQL Code and Optimizing Queries with GPT‑3 Codex. arXiv. Available at: https://arxiv. org/abs/2209.14900. Accessed on: July 20, 2025.
Xu, C., Zhao, Z., Zhou, Y., Huang, S., Jiang, Y., Liu, X., & Gao, J. (2023). EcomGPT: Instruction Tuning for E-commerce Tasks. arXiv. Available at: https://arxiv. org/abs/2305.18278. Accessed on: July 20, 2025.
Zhou, H., Fang, Y., & Liu, Y. (2023). The Dark Side of Chatbot Implementation: Consumer Expectations and Dissatisfaction with Human Service. Computers in Human Behavior, 145, 107773. Available at: https://www. sciencedirect. com/science/article/pii/S0747563223000350. Accessed on: July 20, 2025.
Statistics: 16256 characters • 2355 words
Executive summary from the Final Course Work of the Specialization in Data Science and Analytics of the MBA USP/Esalq
Learn more about the course; click here: