NVIDIANVIDIA-Certified Professional: Agentic AI2026-106.5 Enable real-time access and reasoning over structured and unstructured knowledge.
Constrain SQL and tabular queries
Completed by the knowledge check
Learning objective
Query structured data with text-to-SQL and tabular tools.
Core idea
For an analytics assistant, structured knowledge is something to query, not merely text to retrieve. A database engine can compute a total over every qualifying row; a language model reading a few retrieved rows cannot establish that total. You must choose both the execution mechanism and the meaning of the calculation before accepting the answer.
Text-to-SQL offers flexible joins and aggregation but lets a model propose executable statements. A bounded tabular tool offers fewer operations through an explicit interface, trading flexibility for predictable permissions and cost. Neither approach makes an ambiguous business definition precise automatically. A correct execution can still calculate the wrong metric.
How it works
Discover the schema before generating SQL
LangChain’s SQL-agent example separates four tools: sql_db_list_tables, sql_db_schema, sql_db_query_checker, and sql_db_query. These wrappers are demonstration code, not a secure production interface; production implementations need narrowly scoped database permissions and application-specific validation. The agent lists tables, inspects relevant schemas, generates a dialect-specific query, checks it, executes it, and uses database errors to repair mistakes. Schema inspection includes sample rows, so the database connection must restrict even discovery to data the caller may see.
Check more than column spelling. Establish the table’s grain, the join keys, the meaning of a date, and the units of a measure. Joining one invoice to several line items and then summing the invoice total counts that invoice repeatedly. A successful SQL execution does not detect that semantic error. The data owner should supply a metric definition identifying the source tables, aggregation grain, included statuses, and time zone; the tool implements that definition.
sql_db_query_checker checks common mistakes such as NOT IN with null values, inappropriate UNION, range semantics, and incorrect join columns. It is another model-mediated check, not a database permission mechanism. Use it to improve query quality, then let the restricted connection enforce execution authority.
Offer a tabular interface when the question set is bounded
For a stable dashboard-like question, expose a narrow tool such as the application-defined sales_summary(start_date, end_date). The model supplies only dates; the server injects the authorized region from authenticated identity. Its server-side implementation selects approved columns, binds arguments, executes an approved aggregation, and returns named columns with units and the covered interval. This is a design for your application, not a built-in NVIDIA tool.
Python’s sqlite3.Cursor.execute(sql, parameters) supports binding values with placeholders. Use that mechanism for tool arguments instead of interpolating strings into a query. Values and identifiers are different: the server-injected region and model-supplied dates can be bound values, while a proposed table name should be resolved through the tool’s approved choices. Parameter binding does not turn arbitrary model-generated SQL into an approved query.
For an uploaded table, preserve the file identity and its reporting period in the tool result. Normalize column types before performing arithmetic, and return the operation alongside the result: grouped sum, row count, or filtered selection. The tool’s defined operations keep the model from substituting an unsupported calculation. A file snapshot can answer a historical comparison precisely while being unsuitable for a question about this minute’s inventory.
Bound execution and interpret results
LangChain’s example prompt prohibits data modification, requests relevant columns rather than every column, and limits returned examples using top_k. Treat those instructions as guidance. Scope database permissions narrowly, as the tutorial warns. For a local SQLite snapshot, sqlite3.connect with uri=True and a file URI containing mode=ro opens a read-only database. That protects writes to that database; it does not decide which rows a reader is entitled to inspect.
A small result is not necessarily a cheap query. An aggregate returning one row may scan a large table. For the SQLite snapshot, Python’s Connection.set_progress_handler(callback, n) runs a callback every n SQLite virtual-machine instructions; a nonzero callback result terminates the query with DatabaseError. The snapshot tool can use this to enforce its application deadline. For a warehouse deployment, require the database owner to select and configure the engine’s statement-timeout setting within the request budget. Return an interrupted outcome rather than converting it into a zero total.
Distinguish an empty selection, a null aggregate, a truncated row list, and a failed execution. Before synthesizing an answer, require the tool result to state which occurred. On an unknown-column error, inspect sql_db_schema and correct the query. On permission denial, preserve the denial; rewriting until a broader table answers the question changes the access decision. An unknown-column error sends the agent back to the schema, while a permission denial is preserved rather than repaired.
Key distinctions and trade-offs
| Choice | Deciding condition | Mechanism | Cost or risk |
|---|---|---|---|
| Text-to-SQL | Authorized questions need varied joins and aggregations | Schema discovery, query checking, restricted SQL execution | More model turns and variable database work; semantic join errors |
| Bounded tabular tool | A known metric or small operation set covers the request | Approved query plus bound parameters and typed result columns | Less expressive; metric changes require tool maintenance |
| Retrieved row snippets | The request asks for examples or textual explanation | Selected rows supplied as context | Incomplete coverage cannot establish whole-table totals |
The first two approaches can coexist. Route recurring metrics to explicit tools and reserve text-to-SQL for approved exploratory questions. Keep recurring calculations on the reviewed query path so each request does not need another round of query planning and checking.
Architecture / decision scenario
A retail analytics assistant serves 80 regional managers. Its daily sales_summary path must answer net-sales questions within four seconds and may read only the manager’s authorized region. The warehouse contains 20 million line items; an uploaded CSV contains yesterday’s regional snapshot. These are scenario constraints, not product limits.
One proposal retrieves the 30 most relevant rows and lets the model add their amounts. Another gives the SQL agent unrestricted warehouse credentials. The analytics owner rejects both: 30 rows cannot prove a regional total, and the second option grants more authority than the managers possess.
For the daily question, the team implements sales_summary with region taken from the authenticated request, bound date values, and a reviewed definition of returns and taxes. Its result reports currency, reporting interval, and snapshot time. The CSV tool handles historical comparisons but labels its snapshot; it cannot satisfy a request for sales booked after that snapshot.
An analyst asking an approved cross-category question uses text-to-SQL through a restricted reporting connection. This multi-turn exploratory path has a separate 20-second application budget, including schema inspection, query checking, execution, and synthesis. The database owner configures the warehouse statement timeout within that budget. Route recurring metrics to sales_summary because their four-second SLO cannot spend the exploratory path’s longer budget. If the query is interrupted, the assistant offers a narrower period instead of reporting a partial total. The database owner owns access and execution cost; the analytics owner owns metric meaning.
Common exam traps
- Treating retrieved examples as complete input for an aggregate.
- Confusing a model’s query checker with database authorization.
- Assuming placeholder binding validates arbitrary SQL structure.
- Treating a small result limit as a bound on database work.
- Presenting a file snapshot as live operational state.
- Reporting a failed or interrupted query as an empty result.
What to remember
Use the engine to calculate and the model to select and explain approved operations. Discover schema, define metric semantics, enforce permissions through execution credentials, and distinguish complete results from missing or interrupted work. Choose a bounded tabular tool when its narrower interface covers the business question.
Knowledge check
A logistics company’s assistant answers the same net-revenue question for 40 regional managers every day, using a metric definition that finance has reviewed. Each manager may see only their own region, and the shipments table holds 30 million rows. Which design gives a complete regional total with the most predictable permissions and database cost?
A text-to-SQL assistant reaches the reporting database through an account that can also update and delete rows. The team considers this safe because every statement passes sql_db_query_checker and the system prompt forbids DML statements. What should change before the assistant goes to production?
top_k to cap the rows each statement may returntop_k limits the examples returned, not what a statement may do.An analyst asks a text-to-SQL agent for the total invoiced amount in March. The agent joins invoices to invoice_lines on the foreign key invoice_lines.invoice_id and sums invoices.total. The statement passes the query checker and runs without error, but finance’s report, computed from the same tables, is much lower. What is the most likely cause?
top_k limit cut the rows the sum was computed overNOT IN predicate over null values dropped qualifying rowsNOT IN would remove rows and lower the figure rather than inflate it, and the foreign key is the right column for this join.A tool answers aggregate questions over a local SQLite snapshot and must return within three seconds. One aggregate always returns a single row but sometimes scans for much longer. Which mechanism lets the tool stop that query at its deadline?
LIMIT 1 to the aggregate statement the tool executesmode=rosql_db_query_checker before executionConnection.set_progress_handler calls back every n SQLite virtual-machine instructions, and a nonzero return terminates the query with DatabaseError , so the tool can enforce its own deadline. A single-row result says nothing about how much the engine scans, so a row limit does not bound the work; mode=ro prevents writes to the snapshot, and the checker improves query quality without limiting execution.An exploratory text-to-SQL path runs against a warehouse whose owner configured a statement timeout within the request budget. A cross-category query hits that timeout, and the tool’s current code catches the error and returns a total of 0. How should the tool report this outcome?
References
- LangChain, Build a SQL agent
- Python Software Foundation, sqlite3 — DB-API 2.0 interface for SQLite databases