How to Enable LLMs to Accurately Query Databases with Thousands of Tables
When using Large Language Models (LLMs) to generate SQL for database queries, providing the entire database schema becomes impractical and costly, especially with thousands of tables. This article explores a Retrieval-Augmented Generation (RAG) approach to solve this problem. By organizing metadata into hierarchical summaries, implementing query-driven retrieval, and expanding via table relationships, we can assemble a precise context within a token budget. This method balances query accuracy, cost efficiency, and security for enterprise-level natural language database interactions.
I. Problem Background
Data users frequently need to query databases but may not be familiar with the overall database structure. They want to describe their requirements in natural language and have a Large Language Model (LLM) generate the corresponding SQL. For the model to write correct SQL, it needs to know at least the table names, field names, field types, primary and foreign keys, and the relationships between tables. This information is collectively referred to as metadata.
When the number of tables is small, you can manually feed all the metadata to the model at once. Although this approach consumes more tokens, the process is straightforward and can be used directly.
II. Why Feeding the Entire Database Fails
Feeding the entire database metadata encounters three main issues as the number of tables grows:
- Limited Context Length: Taking a financial database as an example, it contains about 2,300 tables with metadata totaling around 40MB. This volume far exceeds the text length limit that mainstream models can accept in a single request. Even if context windows continue to expand in the future, there is no guarantee that all metadata can be effectively utilized.
- Linear Cost Growth: Based on rough estimates, a single request with full metadata can consume millions of tokens, costing anywhere from a few dollars to tens of dollars. For frequent queries, this cost is unacceptable.
- Interference from Irrelevant Information: When faced with a large number of tables irrelevant to the question, the model is prone to selecting the wrong tables, making incorrect joins, or confusing similar field names. The longer the context, the higher the probability that key information will be ignored.
III. Core Idea: Treating Metadata as Retrievable Knowledge
The solution is to change the delivery method: instead of providing all metadata at once, select the relevant parts on demand based on each specific question. The complete process can be divided into four steps:
- Organize the metadata into a hierarchical structure;
- Retrieve candidate tables based on the user’s question;
- Expand along table relationships to supplement necessary joined tables;
- Assemble the context within a budget and pass it to the model for SQL generation.
This approach aligns with the Retrieval-Augmented Generation (RAG) methodology. The core is shifting from “telling the model everything” to “telling the model the parts relevant to this question.”
IV. Solution 1: Hierarchical Summaries
Metadata can be organized into four layers: Database, Subject Domain, Table, and Field.
The first layer is the Database or Subject Domain. Each subject domain is described in one or two sentences indicating its business scope, such as “Transaction Details,” “Customer Information,” or “Risk Indicators.” The model can use this layer for initial coarse filtering.
The second layer is the Table. A summary is generated for each table, including its business purpose, data granularity (e.g., whether one row represents a single transaction or a single customer), primary key, and common metric fields. Granularity information is particularly important because it directly determines how aggregations and distinct operations are written.
The third layer is the Field. Detailed field information is only provided after a table has been selected, preventing the consumption of large amounts of context during the initial stage.
Using this structure, the model first reads the directory and then drills down layer by layer. The initial context is very small; the complete field information of a table is only loaded when it is confirmed to be needed.
Table summaries can be generated in batches by offline tasks and automatically updated when the table structure changes. These summaries require manual spot-checking because incorrect business descriptions will directly lead to incorrect SQL.
V. Solution 2: Query-Driven Retrieval
While hierarchical summaries solve the “what to look at first” problem, retrieval solves the “which tables to select” problem.
The specific method involves converting each table’s summary and field comments into text vectors and storing them in a vector index. When a user asks a question, the question text is also converted into a vector to retrieve the semantically closest tables.
Semantic retrieval excels at handling synonymous expressions. For example, if a user asks about “customer churn,” but the table comment reads “customer cancellation records,” the two are semantically close and the table can still be retrieved.
However, semantic retrieval is less effective for exact identifiers. Information like table names, business codes, and specific field names is better suited for keyword matching. Combining both methods generally yields more stable results than using either alone. The retrieval results can retain a larger pool of candidate tables (e.g., several dozen) to be filtered in subsequent steps.
VI. Solution 3: Relationship Expansion
Retrieval results typically only contain the main tables directly related to the question, whereas actual queries often require joining other tables, such as linking to a customer information table via a customer ID, or a product classification table via a product ID.
You can build a relationship graph using foreign keys, business codes, and other relationships, expanding one or two hops from the candidate tables to add joined tables to the context. The number of expansion hops must be limited. Too many hops will reintroduce a large number of irrelevant tables, negating the benefits of retrieval.
If relationship information is not explicitly declared in the database, it needs to be supplemented through a data dictionary or manual maintenance. Incorrect relationships are more dangerous than missing ones, so ensuring relationship accuracy should be the top priority.
VII. Implementation Steps and Sample Code
The complete implementation can be divided into five steps:
- Collect Metadata: Read table names, field names, field types, comments, and primary/foreign key information from the data dictionary or database system tables.
- Generate Summaries: Generate business descriptions for each table, and perform manual review for frequently used tables.
- Build Index: Write the summaries into the retrieval index while recording the table name and version number to facilitate incremental updates.
- Assemble Context Online: Complete retrieval, relationship expansion, and budget truncation based on the user’s question.
- Generate and Validate: After the model outputs the SQL, perform a syntax check and read-only validation before executing the query.
Below is the sample code for online context assembly. The functions used are placeholder implementations for illustrating the logic and are not interfaces from any specific library:
def build_context(question, catalog, token_budget):# 1. Retrieve candidate tables based on the question (combining semantic search and keyword matching)candidates = retrieve_tables(question, catalog, top_k=30)# 2. Expand one hop along the relationship graph to supplement joined tablesexpanded = expand_by_relations(candidates, catalog.relations, max_hops=1)# 3. Sort by relevance and assemble table cards one by one within the budgetcontext_parts, used = [], 0for table in rank_by_relevance(expanded, question):card = render_table_card(table) # Table purpose, granularity, fields, types, primary/foreign keyscost = estimate_tokens(card)if used + cost > token_budget:breakcontext_parts.append(card)used += costreturn "\n\n".join(context_parts)
The key point of the code is budget control. Regardless of how many candidate tables are retrieved, the final context cannot exceed the set token limit; any excess is directly truncated.
VIII. Security and Quality Assurance
Both metadata and query capabilities involve sensitive assets, requiring constraints from the following aspects:
- Permission Control: The query account should only be granted read-only permissions and restricted to accessible databases and tables. Statements generated by the model should not have write or delete capabilities.
- Sensitive Information Handling: Fields like ID numbers and bank accounts should be masked. The prompt should only provide field names and types, without real sample values.
- Result Validation: Spot-check the number of returned rows, aggregation logic, and key metrics to confirm the results align with business expectations.
- Audit Logs: Save the user question, retrieved tables, generated SQL, and execution results for issue tracing and performance review.
- Data Localization: If the metadata contains sensitive business information, the relevant processing should be deployed in a compliant environment.
IX. Cost Estimation Method
The number of tokens can be roughly estimated by character count, though actual numbers depend on the tokenizer of the specific model used. The estimation formula for a single request cost is:
Single Cost ≈ Input Tokens × Input Price + Output Tokens × Output Price
Taking the 40MB metadata from the earlier example, if only a small number of tables relevant to the question are retained, the input size can typically be reduced to less than 1% of the original. The cost reduction depends on the number of retrieved tables and the complexity of the fields, and should be measured with actual samples rather than applying a fixed ratio.
X. Conclusion
When a database scale exceeds the model’s context limit, feeding the entire database is neither feasible nor economical. A viable approach is to organize metadata into hierarchical summaries, use query-driven retrieval to find relevant tables, supplement joined information through relationship expansion, and assemble the context within a token budget. Combined with read-only permissions, sensitive field masking, and result auditing, this solution achieves a balance between accuracy, cost, and security.
