The security boundary in text-to-SQL is not the prompt. A model can produce syntactically valid SQL and still query sensitive rows, run a costly scan or invent a misleading business calculation. Reliable enterprise analytics requires a governed path between natural-language intent and database execution.

The security boundary in text-to-SQL is not the prompt. A model can produce syntactically valid SQL and still query sensitive rows, run a costly scan or invent a misleading business calculation. Reliable enterprise analytics requires a governed path between natural-language intent and database execution.
How a governed text-to-SQL request should work
The user asks: “What changed in gross margin for our French enterprise accounts last quarter?” The system resolves identity and tenant, maps business vocabulary to approved metrics, generates a read-only query plan, validates it against policy and only then executes it on approved data. It returns an explanation with metric definitions and query provenance.
The trust boundary stays outside the model: identity, permissions and query execution limits are enforced by infrastructure. A good answer is insufficient if the execution path bypasses row-level security or crosses tenants.

Seven controls to implement in order
Control | Why it matters | Verification |
|---|---|---|
1. Identity binding | Tie every request to the actual person and tenant | Attempt cross-role and cross-tenant access |
2. Semantic definitions | Standardize approved metrics and joins | Compare identical KPI questions across teams |
3. Schema minimization | Hide tables and columns outside the task | Try to request forbidden columns |
4. SQL parsing and allowlists | Reject mutations, risky functions and unsupported statements | AST tests with nested queries and injections |
5. Database enforcement | Apply least privilege, RLS, timeouts and quotas | Prove denied queries fail in database |
6. Result validation | Check types, totals, units and result cardinality | Inject nulls and edge cases |
7. Audit and evaluation | Trace question, policy, SQL, result and feedback | Replay incident with sensitive data redacted |
The semantic layer is a correctness contract
A semantic layer provides shared business definitions such as “net revenue,” “active customer” or “on-time delivery.” It is more than a schema dictionary: it documents calculation logic, approved joins, filters, grain and metric ownership. Without it, two plausible SQL statements can give contradictory answers to the same question.
The semantic layer should be versioned and tied to data lineage. For a definition, see enterprise search for the broader retrieval boundary and the new related definition proposed below, what is a semantic layer for AI agents?
Treat prompt injection as an input threat, not an instruction
An attacker may place instructions inside a database value, a retrieved document or a user question. That text must never rewrite authorization. Use a deterministic validator that understands the parsed query, enforce tenant and role restrictions at the database, and disallow arbitrary DDL/DML and unrestricted functions. OWASP recommends backend permissions, least privilege and explicit authorization on tool calls.
Example of a query approval trace
This is a synthetic illustration. Actual production logs should avoid storing sensitive raw SQL parameters, user secrets or personal data without a lawful basis and protection controls.

Test the system with questions that are designed to fail
Ask for a competitor tenant’s customer-level data. Expected: deny.
Request an unsupported metric with ambiguous grain. Expected: clarify, not fabricate.
Inject SQL instructions inside a source document. Expected: treat as data.
Generate a query that times out. Expected: graceful bounded failure.
Change access between planning and execution. Expected: recheck permission.
Submit the same write-like intent repeatedly. Expected: no execution through a read-only agent.
What to measure during a pilot
Track task success under authorized roles, policy-denial correctness, SQL syntax validity, semantic correctness, p95 query time, error rate, cost per successful question and user escalation. Compare against a stable baseline of analyst-authored queries and business-owned metric definitions.
Deployment checklist
Bind identity and tenant before planning.
Expose only authorized semantic entities and database scopes.
Validate SQL as an AST and enforce limits at the database.
Run read-only credentials and track resource usage.
Persist a redacted evidence chain for every execution.
Block rollout if any high-severity authorization test fails.
A reference deployment boundary for engineering teams
Expose a text-to-SQL agent through a dedicated API that receives authenticated user context from the application, not a role copied out of a chat message. The agent can request a governed semantic query plan, but a separate validator verifies allowed business entities, joins, filters and output grain. The database connection uses a narrowly scoped read-only role, with row-level access policies, statement timeouts and a maximum result size. Return aggregate results with the semantic metric version and a trace identifier. Reject attempts to execute multiple statements or to request resources outside the approved contract.
Why SQL syntax validation is necessary but insufficient
A parser can catch a forbidden UPDATE statement or an unsupported function. It does not necessarily know that “revenue” should exclude refunded orders, that a contract cannot cross regions, or that a customer identifier is personal data. That is why three different controls must cooperate: syntactic query policy, business semantic validation and enforcement of permissions by the database itself. Each failure mode needs a dedicated adversarial test.
Treat derived SQL as an untrusted proposal. Even when it has been produced by a trusted model, validate placeholders, identifier resolution, expanded views, table functions and data volume. Prefer parameterized filters, deny-by-default table access, and policy-aware query compilation. Require the system to explain when a metric definition is missing rather than inventing a plausible calculation.
Operational ownership: who updates what?
Responsibility | Accountable team |
|---|---|
Metric definitions and reporting grain | Business data owner |
Identity, authorization and data classification | Security and platform engineering |
Query planner, validators and agent evaluation | AI engineering |
Database roles, RLS, limits and performance | Data platform operations |
Release approval and incident response | Cross-functional service owner |
This separation makes text-to-SQL a maintained business capability, not an uncontrolled chatbot attached to a database. The technical win is not only more questions answered; it is that answers and attempted actions can be explained, reproduced and challenged safely.
Frequently asked questions
Can prompts alone secure a SQL agent?
No. Access control and query constraints must be enforced independently by backend and database systems.
Why does text-to-SQL need a semantic layer?
It provides shared metric definitions, joins and grain so a syntactically correct query can also be business-correct.
Should a SQL agent have write access?
Read-only access is the safest default for analytics; any write operation requires separate design, authorization and approvals.
What is the safest database permission for an analytics SQL agent?
Start with a narrowly scoped read-only database role, enforce tenant and row-level permissions in the database, and apply statement timeouts and result-size limits.
What should a SQL agent do when a business metric is ambiguous?
Ask for clarification or decline the calculation until an approved semantic definition exists; do not invent metric formulas, joins or reporting grain.
Related definition
Framer is a no-code tool for building and publishing responsive websites—perfect for anyone creating modern, high-performance pages without coding.





















