Executive Summary

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:

Who edited this article

Most recent

You may also like

Executive Mba In Leadership And Management

November 23, 2026

Improvements in the efficiency of a secondary biological sludge drying plant

The management of industrial solid waste, especially secondary biological sludge, represented an operational and strategic challenge for a company in the pulp and paper sector. A secondary biological sludge drying plant, installed to meet environmental requirements and reduce costs, operated with low efficiency and high unavailability. The objective of this study was to evaluate and propose a set of actions to increase the operational availability of the plant, ensure the integral processing of the generated sludge, and reduce treatment and transportation costs, in addition to mitigating environmental risks. To this end, an analysis of the root causes of low efficiency was carried out, using tools such as the cause-and-effect diagram (Ishikawa) and the “5 whys” analysis, and hypotheses were tested to identify the most impactful factors. Three main root causes were identified: addition of low-load effluent to the process, absence of a dedicated maintenance team, and lower consistency of dewatered sludge. The proposed countermeasures, which included stopping the addition of effluent, hiring a maintenance team, and testing polymers, had a monthly implementation cost of R$ 35,000.00. An annual reduction in operating expenses of up to R$ 1,800,000.00 and maintenance costs of R$ 600,000.00 was estimated, in addition to a 25% reduction in operational unavailability. It was concluded that the proposed measures are viable, quick to implement, and capable of ensuring the integral processing of secondary biological sludge, strengthening the company’s ESG strategy and ensuring environmental compliance.

Keywords: Operational costs; Operational efficiency; ESG; Biological sludge; Sludge drying.

Data Science And Analytics For Operations

November 19, 2026

Polyp-YOLO: an efficient, low-latency detector for polyps in colonoscopies

The early detection of colorectal polyps is crucial for the prevention of colorectal cancer, and real-time computer-aided detection (CADe) systems have shown gains in endoscopic practice. The objective was to develop and validate a lightweight colorectal polyp detector, based on the YOLO architecture, capable of operating on restricted hardware with high precision and low latency. The methodology used public datasets of endoscopic images, partitioning the Kvasir-SEG dataset for training and internal validation, and CVC-ClinicDB and ETIS-Larib Polyp DB for cross-dataset evaluation. Lightweight variants of the YOLOv8, YOLO11, and YOLO26 families with 640×640 pixel input were evaluated. A grid search tested 70 combinations of optimizers and activation functions, and identified AdaBelief and LeakyReLU as the configuration with the best generalization. The optimization pipeline applied unstructured pruning, knowledge distillation, and fine-tuning. The optimized YOLO11n-seg model outperformed the higher-capacity architecture (YOLO26m-seg) in mAP50 and showed similar performance in F1-Score, operating with approximately seven times fewer parameters. It achieved an mAP50 of 0.7929 and an F1-Score of 0.7514 on the ETIS-Larib dataset, and fast inference was demonstrated in different formats, with real-time latencies. The explainability of predictions was validated by Grad-CAM activation maps. The proposed solution demonstrated itself to be a promising experimental tool for diagnostic support, with technical feasibility for integration into environments with reduced computational power, although it requires future clinical validation.

Keywords: Computer-aided detection; Edge computing; Hyperparameter optimization; Endoscopic image segmentation; Medical computer vision.

Data Science And Analytics For Operations

November 19, 2026

Multi-touch Attribution in E-commerce: A Comparison between Markov Chains and Last-Click

The research investigated Multi-touch Attribution (MTA) Models in e-commerce, seeking to overcome the limitations of the Last-Click model, widely used in the market. The objective was to compare the performance of first-order Markov Chains with Last-Click and Position-Based approaches, identifying the value of assistance channels frequently ignored. To this end, Markov Chain algorithms were applied to a large volume of purchase journey data from the Google Merchandise Store, extracted via BigQuery. The study probabilistically mapped the purchase journey and calculated the Removal Effect to quantify channel relevance. The results demonstrated that data-driven models identified the strategic role of discovery (awareness) and assistance channels, which Last-Click neglected in 65% of complex journeys. Simulated financial analysis indicated an approximate 28% hidden efficiency in Cost Per Acquisition (CPA) for Paid Search, compared to the Last-Click model. It was concluded that Markov Chains allowed for a more accurate mapping of purchase journeys, validating the technical feasibility of the modeling and providing evidence for more efficient budget allocation in digital media, mitigating the risk of early divestment in crucial channels.

Keywords: Assistance channels; Data science; E-commerce; Digital marketing; Media optimization.

Project Management

November 19, 2026

Integrated Software for Operational Communication and Control: Practical Evidence in a Medium-Sized Company

The study analyzed the impacts of the lack of integration between commercial and operational modules of an integrated management software (ERP/CRM) in a medium-sized company in the mechanical engineering sector. The main objective was to evaluate practical evidence of communication and operational control optimization, identify bottlenecks, and formulate improvement proposals. A qualitative-quantitative approach was adopted through a single case study with documentary research, based on the extraction and filtering of historical task records from the Bitrix24 software and statistical correlation analysis between workload and allocated team. Based on the diagnosis, an action plan structured in the 5W2H tool was developed. The results revealed that 54.4% of the registered tasks consisted of duplicate, test, or practically useless records, generated by manual insertion during the scope transition between commercial CRM and engineering. It was also demonstrated that the increase in the commercial team linearly accompanied the growth of inefficient tasks, polluting the database and masking the organization’s real productive capacity. It was concluded that the automation of workflows and native integration between modules are essential to mitigate operational and financial risks, providing replicable guidelines for data governance in small and medium-sized enterprises.

Keywords: System Customization; Enterprise Resource Planning (ERP); Task Management; Management Software.

Project Management

November 19, 2026

Supervised learning in voltammetric quantification with electrochemical sensors

The application of supervised learning in the voltammetric quantification of paraquat in artificial urine was evaluated. The study aimed to quantitatively assess the predictive performance of supervised learning models compared to a univariate “baseline”, preserving independence between devices in the training and testing sets. The research was conducted as an applied case study, processing data from four physical devices, each evaluated under a blank condition and six paraquat concentration levels, totaling 28 square wave voltammetry (SWV) curves. A computational “pipeline” integrated automated file reading, organization of curves into current-potential matrices, generation of potential maps, and device-specific blank correction. Five approaches were considered: conventional univariate calibration, predictive univariate “baseline”, partial least squares (PLS) regression, support vector regression (SVR), and random forest (RF). Predictive evaluation was performed using device-grouped cross-validation. PLS showed the best predictive performance for curves from a device not used in training, with an R² of 0.7981. RF exhibited intermediate performance, while SVR and the predictive univariate “baseline” showed inferior and similar performance between themselves. It was concluded that a compact multivariate representation of the voltammetric profile was more favorable for inter-device prediction than increasing model flexibility under the studied conditions. Grouped validation preserved independence, but the limited number of devices restricts the generalization of results.

Keywords: Supervised learning; Paraquat; PLS; Electrochemical sensors; Square wave voltammetry.

Project Management

November 19, 2026

Improvement of Inventory Management via Lean Six Sigma: Study in the Paper Industry

Organizations seek methodologies to reduce waste, increase efficiency, and become more competitive, promoting sustainable improvements in their processes. In this context, the study aimed to apply the Lean Six Sigma methodology, through the DMAIC cycle, to improve inventory management in a company in the paper industry manufacturing pneumatic hoses, aiming to increase the accuracy between physical and systemic inventories and improve the visual management of parts storage. The research was developed from the collection and analysis of data extracted from the company’s ERP system. Tools such as SIPOC, Ishikawa Diagram, and 5 Whys were used to define and identify the root cause of the problem. As improvement proposals, a Digital Kanban system and an adaptation of the Two-Bin system, called the Three-Bin System, were implemented, in addition to the development of standardized operating procedures and the establishment of control mechanisms. The results demonstrated a significant improvement in inventory accuracy, raising the lowest identified index from 28% to 80%, and detected discrepancies between systemic and physical records equivalent to R$ 134,335.53. It was concluded that the application of Lean Six Sigma, combined with Project Management, represented an effective approach for conducting operational improvement projects, contributed to increased reliability of inventory information, to the improvement of material control processes, and to the strengthening of the organization’s operational management.

Keywords: Inventory accuracy; DMAIC; Visual management.

Data Science And Analytics For Operations

November 19, 2026

Predictive Analysis Methodology for Performance Optimization in E-commerce: Correlation between Public Data and Paid Media

A predictive analysis methodology was developed for e-commerce, integrating transactional data and public search trends. The objective was to develop and validate a predictive model, based on machine learning algorithms, capable of correlating organic search trends with sales performance and paid media costs in the Beauty and Health category of Brazilian e-commerce. The Brazilian E-Commerce Public Dataset by Olist and data from Google Trends were used, processed in Python with the Random Forest Regressor algorithm. A moderate inverse correlation (r = -0.43) with a seven-day lag was identified between organic search volume and purchase. Initial models, based solely on behavioral variables, presented insufficient metrics (R² = -0.47; MAE of R$ 2,120.54). The incorporation of microeconomic (average ticket and shipping) and macroeconomic (exchange rate and Ibovespa index) variables raised the R² of the final model to 0.29, with an MAE of R$ 1,489.63, representing a 24.7% reduction in error compared to the baseline. Temporal cross-validation showed that, in periods of mature operation (2018), the model achieved an R² of 0.42. It was concluded that isolated search volume explains the moment of consumer interest, but not the financial magnitude of sales, making the fusion with transactional and economic data mandatory for predictive viability.

Keywords: Beauty and Health; Consumer Behavior; Google Trends; Machine Learning; Time Series.