October 26, 2026
SQL query optimization with large language models
Ramon Albernaz dos Santos; Eduardo Mendes
DOI: 10.22167/2675-6528-202603390
Article derived from a Course Conclusion Work (TCC), with content based on the student’s original work and adapted to the editorial format of the E&S Magazine with the support of the ResumeAI tool, an artificial intelligence solution developed by Instituto Pecege for textual synthesis and organization.
Summary
The growing complexity of relational database management systems and the massive volume of data have made SQL query optimization a challenging task. A study analyzed the effectiveness of generative artificial intelligence in proposing performance improvements in queries, considering different scenarios. To this end, a web application was developed and evaluated that used large language models (LLMs) integrated with a Retrieval-Augmented Generation (RAG) technique to optimize SQL queries. The application consumed LLMs to suggest indexes and syntactic rewrites based on technical contexts retrieved from a vector database. The results indicated that the application achieved linear success in small-scale environments. However, in larger volumes, such as ten gigabytes, performance regressions were observed, attributed to inefficient database optimizer choices induced by new indexes. It was concluded that the use of LLMs for SQL optimization is a promising tool for decision support, but requires professional supervision.
Keywords: Gemini 2.5 Flash; Gemma 3; Indexes; Generative Artificial Intelligence; RAG.
1. Introduction
The digital age is marked by the growing complexity of relational database management systems and the massive volume of data, which have consolidated as fundamental pillars for the innovation and growth of organizations. The analysis of large volumes of data has the potential to generate significant economic value, providing
understandings
to improve internal processes and develop new products or services, as pointed out by McKinsey Global Institute (2011). Recent studies, such as Rauf et al. (2024), demonstrate that the adoption of Big Data can result in a 25% improvement in decision-making efficiency and a reduction in data processing in companies.
However, the mere possession of data is not enough; the ability to access and analyze it quickly and efficiently is crucial for gaining competitive advantages. The speed of database queries is a determining factor in accelerating the application of data science in organizational operations. Unsatisfactory performance queries directly impact operational efficiency, and query optimization can improve performance by 80%, in addition to a correct definition of data types potentially saving 50% of storage, according to Gupta et al. (2024).
Although several database management systems (DBMS) that use structured query language (SQL) are optimized for their purposes, employing execution plans to enhance performance, these optimizations are not always sufficient for professionals’ daily tasks. Factors such as the number of records, table structure, and the complexity of relationships can negatively impact performance. The very way a query is written can hinder the creation of an optimized execution plan by the DBMS, as illustrated by Mehta et al. (2018), who demonstrate that a simple query can have its execution time drastically altered by its construction.
In this scenario, emerging technologies such as Artificial Intelligence (AI) and Machine Learning (ML) are being explored to solve problems in innovative ways. Large Language Models (LLMs), which are ML models trained with vast amounts of data, are capable of understanding specific contexts and assisting in content generation and task execution, including code generation for software development (IBM). The ability of these models to learn structures and patterns allows them to be trained to analyze SQL queries, identify performance bottlenecks, and suggest changes such as rewriting the query or creating indexes.
Recent studies have explored the potential of AI in query optimization. Abbasi et al. (2024) investigated the integration of machine learning in query generation for PostgreSQL, demonstrating a 55% improvement in the execution time of complex analytical queries. Naha et al. (2025) used the ChatGPT-40 model to compare the equivalence of SQL queries and generate explanatory scenarios. Furthermore, the Retrieval Augmented Generation (RAG) technique emerges as a process that optimizes the output of a large-scale language model, allowing it to consult an external and reliable knowledge base before generating a response (Amazon Web Services).
Despite the advancement of these technologies, a search for “SQL Optimization with LLM” in academic and scientific sources reveals that existing studies predominantly focus on the translation of natural language to SQL. Although there are commercial products and articles on Google about “SQL Optimization with AI”, the lack of scientific evidence on the optimization of SQL queries by LLMs is notable. This research gap raises questions about how large language models can effectively contribute to optimizing SQL queries in databases, increasing execution performance and the value generated for organizations.
Considering the gap in scientific studies on the optimization of SQL queries with large language models, this work is justified by the need to explore the potential of these technologies to increase execution performance and generate value for organizations. The objective of this work is to develop an LLM-based solution using prompt engineering and RAG techniques for the optimization of SQL queries in PostgreSQL databases, providing a tool that can assist data science professionals in their work routines, generating value for organizations.
2. Material and Methods
The research was characterized by an applied nature and experimental approach, focused on the development and evaluation of a technological solution. The central objective was to develop and test a tool based on Large Language Models (LLMs) to optimize SQL queries in PostgreSQL databases, employing prompt engineering techniques and Retrieval-Augmented Generation (RAG). The methodology was structured in sequential steps, covering model selection, data preparation, application development, and comparative testing cycles.
Initially, the large-scale language model was selected. After a survey of available architectures, categorized into Closed Models (Software as a Service) and Open Weight Models (execution on own infrastructure), Gemma 3 1B was chosen. This open weight model, based on Gemini 2.0 technology, was selected for its ability to run on modest hardware, using 1 billion parameters, and was orchestrated locally through the open-source Ollama ecosystem.
To evaluate the model’s effectiveness, the BIRD benchmark dataset (Big Bench for LaRge-scale Database Grounded Text-to-SQL Evaluation) was used. A structured database in the retail domain was selected, which included entities such as items, orders, and suppliers. The database had heterogeneous volume, with records ranging from 25 units to 4 million rows, and was migrated from SQLite format to PostgreSQL. During the transposition, primary and foreign keys were intentionally suppressed in some tables to test the model’s ability to recommend their creation as an optimization measure.
The prompt engineering stage was crucial for conditioning the LLM’s output. The prompt was configured as a set of input instructions that integrated the user’s SQL query, table schemas, and optimization guidelines. This structure instructed the model to prioritize reducing execution time and computational cost, suggesting indexes or query rewrites based on data engineering best practices, aiming to mitigate hallucinations and ensure the applicability of recommendations to the PostgreSQL environment.
Subsequently, the Retrieval Augmented Generation (RAG) technique was applied to enrich the LLM’s context with external knowledge. The official PostgreSQL manual was incorporated as a knowledge base, using the nomic-embed-text model for embedding generation. The processing flow, developed in Python, consisted of vectorizing the manual and persisting this data in ChromaDB, a vector database. The prompt was restructured to dynamically integrate relevant context retrieved from the manual, mitigating hallucinations and grounding responses in technical documentation.
The technical implementation of the solution was carried out on a personal computer, using the Python programming language. The Ollama library was employed for orchestration and communication with the LLM, and Visual Studio Code (IDE) was used for application development. The web application was developed with a Python back-end, hosted on the Render platform, and a React and Next.js front-end, hosted on the Vercel platform. The interface allowed the insertion of the database schema and the SQL query, displaying the optimized query and the insights generated by the LLM.
The initial tests were segmented into three stages. Firstly, the Gemma 3 model generated six synthetic SQL queries with grouping, filtering, and join operations. These queries were submitted to PostgreSQL for extracting performance metrics, such as execution time and execution plan, establishing a baseline. In the second stage, the original queries and schemas were provided to the LLM via API, using structured prompts. The third stage replicated the procedure, but with the integrated RAG architecture, allowing for a comparison of the LLM’s performance with and without the supplementary knowledge base.
Due to limitations of the Gemma 3 1B model in processing extensive schemas and logical coherence, and local hardware constraints, the transition was made to the Gemini 2.5 Flash model, a closed-weight model operated via cloud, based on the Gemini 2.0 architecture. This change required adaptations in the source code, with the implementation of the langchain_google_genai library for communication with the Gemini API. Local RAG tools were replaced by the Google embeddings API, specifically the gemini-embedding-001 model, and the vector knowledge base was migrated to the Pinecone platform.
With the model transition, the query generation step was reiterated to ensure the consistency of the new experiments, requesting Gemini 2.5 Flash to create six SQL instructions with performance bottlenecks. A new baseline data collection was performed, executing the queries on a PostgreSQL database in its original state, without indexes or keys. Performance metrics, including execution time, operational costs, and buffer usage, were obtained using the `EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)` statistical command.
To ensure the isolation and neutralization of external variables, Docker containers were used for test execution. For each of the six queries, the container was destroyed and recreated from a clean backup of the database, ensuring that each execution occurred in a clean environment. Subsequently, the web application interface was used to process the query optimization with the LLM. The obtained responses, containing the rewritten versions and infrastructure suggestions, were subjected to the same rigorous flow with Docker. For each optimization, the database was restored, and before executing the final query, the scripts for creating indexes or extensions recommended by the model were applied, allowing for a precise comparison between the original and optimized states.
To confer greater robustness to the results, TPC-H, a decision support benchmark, was incorporated into the research. Version 3.0.1 of the tool was used, which provided a scalable data generator (dbgen) and a query generator (qgen). The latter allowed the creation of twenty-two standardized queries, designed to simulate complex scenarios of operational bottlenecks. A database with a volume of ten gigabytes was generated, representing a tenfold increase compared to the data mass used in the previous stages. The generated queries were subjected to specific adjustments to ensure syntactic compliance with the PostgreSQL dialect.
With the new environment configured, the test cycles were replicated following the established pattern. For each of the twenty-two queries, the database was restored in isolation within a Docker container, where the SQL statement was executed under monitoring of the metrics extraction command. The queries were processed by the web application for the optimization step. The final test battery followed the same isolation protocol: for each scenario proposed by the LLM, the container was restarted, the suggested indexes and extensions were created, and finally, the optimized query was executed.
3. Results and Discussion
The initial data collection stage employed the Gemma 3 model to optimize six SQL queries, which were generated by the model itself from a provided database schema. It was observed that the model was capable of producing instructions that were mostly efficient in terms of execution time. However, two of the six generated queries presented significant structural inconsistencies. In one case, the model performed a grouping by the table’s primary key but omitted the selected field in the GROUP BY clause, resulting in an execution error in PostgreSQL. In the second case, the query was generated without specifying fields in the SELECT clause, although syntactically valid, resulting in an empty dataset. These occurrences suggested limitations of Gemma 3 in maintaining the context window or in accurately interpreting schema constraints during the inference process.
The prompt engineering technique was applied with the objective of optimizing SQL code and generating technical insights. Four out of six queries remained unchanged, with the model indicating they were already optimized. In one scenario, Gemma 3 corrected the omission of a field in the grouping clause. However, failures to adhere to prompt constraints were identified, such as the addition of an unsolicited field in the SELECT clause and the introduction of syntactically erroneous aggregation functions, making execution impossible. In contrast, the generation of technical recommendations, such as the creation of secondary indexes for joins, groupings, and filters, showed a high success rate, with CREATE INDEX scripts provided. The model also proposed table partitioning strategies for high-volume scenarios, grounding PostgreSQL’s efficiency in indexing. The application of B-Tree based indexes reduces search cost to O(log n) logarithmic complexity, maintaining performance with exponential data growth.
The validation of index suggestions, implemented in the test database, resulted in inconclusive performance. Marginal oscillations of increase and subtle reductions in execution time were observed. This low variance was attributed to the reduced scale of the database and the low computational complexity of the queries, factors that limited the potential performance gain of indexing in production environments. The integration of the official PostgreSQL manual via Retrieval-Augmented Generation (RAG) for query optimization presented heterogeneous results and lower consistency. Although the model maintained adequate patterns in recommending indexes and partitioning strategies, regressions were noted in syntactic correction tasks and adherence to the provided schema. In one of the scenarios, Gemma 3 recommended the creation of indexes with incorrect syntax, making direct script application unfeasible. Additionally, data hallucination occurred, with the model stating the existence of foreign keys not present in the provided schema, and a loss of effectiveness in correcting structural errors, altering the original result set.
The analysis of the execution times of queries optimized by Gemma 3, according to the collected data, revealed a mixed behavior. In scenario 1, the original time of 220 ms increased to 281 ms with the prompt and went to 229 ms with RAG, presenting hallucination. Scenario 2, with 662 ms originally, rose to 5061 ms with the prompt and 680 ms with RAG, also with hallucination. Scenario 3, with 903 ms, was optimized to 485 ms with the prompt and 395 ms with RAG, without hallucination. Scenario 4, of 95 ms, went to 106 ms with the prompt and 182 ms with RAG, without hallucination. Scenario 5, with 276 ms, reduced to 50 ms with the prompt, without RAG and without hallucination. Scenario 6, which presented an error in prompt optimization, had an original time of 276 ms and a time of 5876 ms with RAG, with hallucination. These results indicated that, when exposed to a high volume of information via RAG, the model’s context maintenance capacity may be compromised, affecting the accuracy of outputs and suggesting a possible saturation of the context window or difficulty in prioritizing prompt instructions over retrieved data.
Given the unsatisfactory results of Gemma 3 in terms of accuracy and optimization complexity, and the hardware constraints that prevented the execution of more robust variants, the decision was made to transition to the Gemini 2.5 Flash model. This choice was justified by technological parity with the Gemma family and a significantly superior context window, in addition to a greater reasoning capacity. The methodological change required adaptations in the application’s source code, including the implementation of the langchain_google_genai library for communication with the Gemini API and prompt simplification. For the RAG architecture, local tools were replaced by Google’s embedding API, specifically the gemini-embedding-001 model, optimized for capturing semantic nuances in technical documentation. This transition allowed for the vectorization of the PostgreSQL manual with greater information density, facilitating similarity search and providing more precise contexts for the model’s response generation.
A new battery of tests was performed with Gemini 2.5 Flash, using Docker containers to ensure a clean and isolated environment for each execution, neutralizing external variables such as memory cache. For this battery, queries were generated that presented performance challenges, such as correlated subqueries and sequential searches in large tables. An example of a generated query performed a sub-select on the `public.lineitem` table for each record in `public.part`, resulting in a complexity of order O(n²) and a runtime that exceeded six hours in the Docker environment, without being able to finish or generate an execution plan. This confirmed the presence of critical performance bottlenecks in the original queries.
When submitting the original query with bottlenecks to the web application with Gemini 2.5 Flash, the model returned a rewritten version using a JOIN between the tables and a Common Table Expression (CTE) to replace the subquery, in addition to suggesting the creation of indexes on the `p_size` columns of the `public.part` table and `p_part_partkey` of the `public.line_item` table. The execution of the optimized query, after creating the indexes, resulted in a runtime of 1.8 seconds, demonstrating a significant improvement compared to the original runtime, which did not complete. The comparison of records returned by the optimized query showed a divergence in ordering, which may be related to the indexing done by PostgreSQL, but did not alter the expected return for the user in queries without an explicit ordering field.
The query runtimes optimized by Gemini 2.5 Flash showed significant improvements. In scenario 1, the original time of 4.99 seconds was reduced to 2.31 seconds, a difference of -53.71%. Scenario 2, at 89.93 milliseconds, was optimized to 0.759 milliseconds, a reduction of -99.16%. Scenario 3, which originally did not finish (timeout), was executed in 1.85 seconds. Scenario 4, at 1.39 seconds, was reduced to 0.72 milliseconds, an improvement of -99.95%. Scenario 5, at 5.08 milliseconds, went to 1.23 milliseconds (-75.74%). Finally, scenario 6, at 902.4 milliseconds, was optimized to 232.34 milliseconds (-74.25%). These results highlight the high efficiency of the Gemini 2.5 Flash model in optimizing queries in smaller-scale environments.
The analysis of the estimated total costs in the execution plan of the optimized queries also revealed notable reductions. In scenario 1, the original cost of 17,927,093.59 was drastically reduced to 678,721.81, a difference of -96.21%. Scenario 2 had a reduction from 4,066.40 to 1,858.73 (-54.29%). Scenario 3, which originally presented a timeout, had a cost of 13,689,480.38 in the optimized version. Scenario 4, with an original cost of 98,726.63, was optimized to 9.90 (-99.99%). Scenario 5 reduced from 239.20 to 133.75 (-44.09%), and scenario 6 from 56,565.03 to 23,708.26 (-58.09%). This cost reduction, in some cases close to 100%, reinforces the effectiveness of the proposed optimizations and explains the decrease in execution time. Memory metrics also indicated that the execution plan used memory in some scenarios, which can be attributed to the existence of indexes.
The final testing stage used the TPC-H benchmark with a 10 GB database and 22 queries, with a 20-minute execution time limit. The results were inconsistent, with several queries showing longer execution times after optimization. However, it is important to note that queries that previously exceeded the time limit (scenarios 2, 17, 20, and 21) were executed in seconds after optimization. Scenario 22, on the other hand, showed the greatest deterioration, with an increase of over 4,000% in execution time. This inconsistency can be attributed to factors such as the ten times larger database, the greater syntactic complexity of the queries, and the limited processing power of the personal computer used for testing, even with the Docker configuration.
The analysis of the execution plans for scenario 22, which showed the greatest deterioration, revealed one of the causes. The original plan used the Parallel Hash Right Anti Join technique to read five million records from the `orders` table in parallel. The optimization suggested by the model, which included creating indexes and replacing subqueries with Common Table Expressions (CTE), led the execution plan to replace parallelization with a nested loop that accessed the created index approximately 190 thousand times. Although the total cost in the execution plan was reduced by just over six percent, the execution time increased drastically, indicating that lower cost does not always translate into faster execution time. This demonstrates the complexity of optimization in high-volume scenarios, where the database optimizer’s choices can be counter-intuitive.
The replacement of the Gemma 3 1B model with Gemini 2.5 Flash demonstrated excellent results in query optimization, even when using the same architecture of the Gemini family. One of the decisive factors was the context window of Gemini 2.5 Flash, which is one million tokens, significantly larger than Gemma 3’s 32 thousand tokens. Furthermore, Gemini 2.5 Flash did not exhibit hallucinations, maintaining the structural consistency of the responses. All model suggestions were based on the PostgreSQL manual, as instructed, indicating that the recommendations were derived from the RAG used. Scenarios that previously exceeded the 20-minute limit were executed in seconds, and scenario 22, despite a deterioration in runtime, was optimized by over 4,000% compared to its original timeout time.
The application developed for the model tests, although efficient in smaller databases, proved less effective in larger environments, such as the 10 GB one. In this context, including the execution plan as input information for the model could yield more positive impacts, providing data on the number of records and the execution strategies used. Another suggestion to enhance the model’s capability would be integration with a model specifically trained for SQL optimization and a database through a Query Processing Engine (QPE). In summary, the results indicate that the use of LLMs, especially more robust models like Gemini 2.5 Flash with RAG, is a promising tool to assist in SQL query optimization, offering significant performance gains and technical insights, but requires professional supervision to ensure integrity and effectiveness in complex and high-volume environments, where the optimizer’s behavior can be unpredictable.
4. Conclusion
This study aimed to develop a solution based on large language models (LLMs) and Retrieval Augmented Generation (RAG) techniques to optimize SQL queries in PostgreSQL databases, assisting data science professionals. It was found that the application, by employing the Gemini 2.5 Flash model, demonstrated high efficacy in smaller-scale environments, promoting significant reductions in execution time and operational costs for complex queries. It was identified that queries that previously resulted in timeouts were executed in seconds, and others showed performance improvements exceeding 99%. Optimizations included rewriting inefficient subqueries into joins and Common Table Expressions (CTEs), as well as proposing secondary indexes based on the PostgreSQL manual, which highlighted the model’s ability to generate precise and well-founded technical insights.
However, limitations were observed in high-volume scenarios, such as in ten-gigabyte databases, where optimization resulted in performance regressions for some queries. This inconsistency was attributed to counter-intuitive choices by the database optimizer, induced by the new indexes, and to the syntactic complexity of large-scale queries. Initial experience with the Gemma 3 model also revealed challenges related to maintaining the context window, hallucinations, and syntactic errors, highlighting the importance of model robustness. Thus, although the LLM-based solution with RAG is a promising tool for decision support and the generation of diagnostics and indexing scripts, its application in complex and high-volume environments requires professional supervision. For future studies, it is suggested to include the execution plan as input for the model and to integrate with a Query Processing Engine (QPE) to enhance large-scale optimization.
Bibliographic References
Abbasi M.; Bernardo M.V.; Váz P.; Silva J.; Martins P. 2024. Adaptive and Scalable Database Management with Machine Learning Integration: A PostgreSQL Case Study. Information 15(9): 574.
Gupta M.; Mittal A.; Bisht S.S.; Arora S. 2024. Optimizing MySQL Performance: Essential Techniques, Resources, and Best Practices. In: International Conference on Progressive Innovations in Intelligent Systems and Data Science (ICPIDS), 2024, Pattaya, Tailândia. Anais… p. 484-489.
McKinsey Global Institute [MGI]. 2011. Big data: the next frontier for innovation, competition, and productivity. Disponível em: <https://www.mckinsey.com/capabilities/mckinsey-digital/our-insights/big-data-the-next-frontie r-for-innovation>. Acesso em: 21 set. 2025.
Mehta S.; Kaur P.; Lodhi P.; Mishra O. 2018. Empirical Evidence of Heuristic and Cost Based Query Optimizations in Relational Databases. In: International Conference on Contemporary Computing (IC3), 2018, Noida, India. Proceedings… p. 1-3.
Naha K.; Rubaiat S. Y.; Jamil H. M. 2025. Are Large Language Models Smart Enough for SQL Tutoring and Assessment?. In: IEEE International Conference on Advanced Learning Technologies (ICALT), 2025, Changhua, Taiwan. Proceedings… p. 357-359.
Rauf A.; Shorna S.A.; Joy Z.H.; Rahman M. 2024. Data-driven transformation: Optimizing enterprise financial management and decisionmaking with Big Data. Academic Journal on Business Administration, Innovation & Sustainability 4(2): 94-106.
Article originating from the Final Course Work of the Specialization in Software Engineering of the MBA USP/Esalq
To learn more about the course, click here and access the MBX Academy platform