How Large Language Models Read Databases with Thousands of Tables
This article explains how to give large language models the right database context when a schema has thousands of tables and full metadata cannot fit into the context window. It covers metadata governance, hybrid retrieval with vector, keyword, and graph expansion, tiered context assembly under a token budget, validation loops with self-correction, and security and cost boundaries, plus common mistakes to avoid.
1. The Real Problem: Not Model Intelligence, but Context Capacity
In enterprise data environments, a mid-sized analytical database often contains more than two thousand tables. Its full metadata (table names, column names, types, comments, primary and foreign keys, partition information, statistics) can easily reach tens of megabytes. Mainstream large language models currently offer context windows on the order of hundreds of thousands of tokens, so injecting everything at once is physically impossible. Even if windows keep growing, a single request that consumes millions of tokens brings latency and cost that make the approach unworkable in engineering terms.
The problem is therefore redefined: how to select the minimum sufficient set of information needed to answer a question within a limited context budget. This is an information retrieval and context engineering problem, not merely a prompt engineering trick.
2. Layer One: Treat Metadata as a First-Class Citizen
Metadata can only be fed to a model if it is fit to be fed. In most enterprise databases, metadata is semi-disordered: missing comments, inconsistent naming, duplicate synonymous columns, and legacy tables mixed with tables in active use. Four steps are recommended first.
- Extract metadata and model it uniformly. Export tables, columns, types, constraints, indexes, and partition keys from the system catalog into a structured intermediate layer. Fields should include at least: schema name, table name, column name, data type, nullability, default value, comment, business domain tag, update frequency, and row count magnitude.
- Fill in semantic information. Add a one-sentence business definition for each table, and clarify enum meanings and units for key columns (for example, currency unit, time zone, currency). This step usually affects generation accuracy more than switching models does.
- Make relationships explicit. Organize primary and foreign keys, plus implicit relationships (identically named columns, naming conventions), into a graph structure: tables are nodes, and edges carry join keys and cardinality (1:1, 1:N, N:M).
- Tier by hotness and coldness. Classify tables into core fact tables, frequently used dimension tables, low-frequency detail tables, and deprecated tables. The tiering result directly determines retrieval priority later.
A schematic metadata structure (pseudocode):
Table {schema, name, comment, domain_tag,row_estimate, update_freq, tier(core|dim|rare|deprecated),columns: [{name, type, nullable, comment, unit, enum_ref}],joins: [{to_table, on_keys, cardinality}]}
3. Layer Two: Retrieve Instead of Injecting Everything
Once metadata is well governed, it can be treated as a searchable knowledge base. A common industrial combination is “vector recall + keyword recall + graph expansion”.
- Vector recall: concatenate table comments, column comments, and business terms into text, chunk it, and write it into a vector index; embed the user question and take the Top-K.
- Keyword recall: tokenize and build inverted matches over table and column names, covering proprietary abbreviations and pinyin-based naming that vector models handle poorly.
- Graph expansion: after a few tables are hit, expand one or two hops along relationship edges to pull in directly related dimension tables, avoiding the case where the fact table is selected but the dimension table is missed.
- Reranking: rerank candidates with a cross-encoder or rule-based scoring (business domain match, tier level, historical click-through rate), keeping only a small number of tables.
A practical recall pipeline:
question-> normalization (disambiguation, time range completion, metric identification)-> parallel recall (vector Top-N / keyword Top-M)-> merge and deduplicate -> one-hop graph expansion-> rerank -> truncate to Top-K (K is usually 3-8)-> assemble context
In engineering practice, keep K small, because recalling too many tables introduces distracting columns and actually lowers the accuracy of table and column selection.
4. Layer Three: Tiered Assembly Under a Context Budget
Selected tables should also be trimmed by information density before entering the prompt, in three progressive levels:
- L1 overview: table name plus a one-sentence comment plus business domain only, so the model can perform table selection first.
- L2 structure: column names, types, key enums, and primary and foreign keys of the target tables, used to generate the query.
- L3 detail: sampled rows, statistics (min and max values, common filter values), and view or wide-table definitions, appended on demand only when needed.
A two-stage prompt is usually more stable than a single injection: the first stage has the model output the list of required tables and columns with reasons; the second stage injects only the L2/L3 information for those structures and generates the final statement. This compresses tokens and makes the selection process auditable.
Constraints should also be stated explicitly: dialect and function whitelist, no full table scans, time columns must carry a filter, calculation definitions for amounts and ratios, and a result row limit. Writing constraints into the system prompt is cheaper than patching things afterward.
5. Layer Four: Validation Loop and Self-Correction
Generation does not equal usability. A closed loop is recommended:
- Static validation: syntax parsing, table and column existence checks, type compatibility checks.
- Semantic validation: execution plan estimation to identify Cartesian products, missing join conditions, and abnormal scan volume.
- Result validation: small-sample trial runs comparing row counts and null rates; regression tests on calculation definitions for key metrics.
- Feedback correction: feed error information (desensitized error messages and execution plan summaries) back to the model with a limited number of retries to avoid infinite loops.
Accumulating a sample set of “question, statement, adopted or not” can be reused continuously for prompt optimization and retrieval reranking training.
6. Layer Five: Security, Permissions, and Cost Boundaries
Feeding a database to a model must have security built in: metadata desensitization (removing real values from sensitive column comments), trimming the visible table scope by role, granting read-only accounts only, enforcing row-level and column-level permissions, intercepting dangerous operations in generated statements, and keeping audit trails across the whole chain. On the cost side, introduce caching (statement caching for identical questions, retrieval result caching) and a tiered model strategy (small models for recall and rewriting, large models for final generation) to push per-request cost into an acceptable range.
7. Common Mistakes
- Blindly increasing K on the assumption that “more input means more accuracy”, which in fact introduces noise.
- Feeding only table structures without business definitions, producing statements that are syntactically correct but wrong in result.
- Ignoring dialect differences and function support ranges, generating statements that cannot execute.
- Having no validation loop and releasing generated results directly to business users.
8. Conclusion
Feeding a database to a large language model is not about stuffing in more information; it is about building a pipeline that runs from metadata governance through hybrid retrieval and tiered assembly to validation and correction. With general capabilities available on cloud platforms such as Baidu AI Cloud, categories like vector search, object storage, containerized services, and monitoring and alerting can be combined into a complete solution, letting users without a database expert background retrieve the data they want through natural language in a stable, secure, and low-cost way.
