Skip to lesson

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.

An unknown-column error sends the agent back to the schema, while a permission denial is preservedThe agent lists tables, inspects relevant schemas, generates a dialect-specific query, checks common mistakes and executes it. An unknown-column error loops back to schema inspection. A permission denial ends in preserving the denial. Before an answer is synthesized, the tool result states which occurred.unknown-column errorpermission denialList tablesInspect relevantschemasGenerate adialect-specificqueryCheck commonmistakesExecute itPreserve the denialState whichoccurredSynthesize ananswer

Key distinctions and trade-offs

ChoiceDeciding conditionMechanismCost or risk
Text-to-SQLAuthorized questions need varied joins and aggregationsSchema discovery, query checking, restricted SQL executionMore model turns and variable database work; semantic join errors
Bounded tabular toolA known metric or small operation set covers the requestApproved query plus bound parameters and typed result columnsLess expressive; metric changes require tool maintenance
Retrieved row snippetsThe request asks for examples or textual explanationSelected rows supplied as contextIncomplete 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

References