Join our Newsletter — 33% off our NHI Course
Home› Guides› SQL Injection vs Prompt Injection: Why Parameterisation Has…
Guide LLM & GenAI Security

SQL Injection vs Prompt Injection: Why Parameterisation Has No LLM Equivalent

← All guides
By NHI Mgmt Group, edited by Lalit Choda Updated 14 November 2026 17 min read
On this page

Teams that learned to beat SQL injection with parameterised queries keep looking for the prompt equivalent, and there is not one. Both flaws come from mixing trusted instructions with untrusted data in one channel, which is why the comparison is so tempting. The difference is that a database has a grammar and a parser that can keep the two apart, and a large language model does not. This guide explains that difference at the level a security architect needs to design controls: why bind variables work, why delimiters, roles and structured prompts are not the same thing, which SQL-era controls carry over (least privilege, output handling, authorisation at the tool boundary) and why filter-only defences fail. For the attack techniques themselves, see the Prompt Injection Guide and the SQL Injection Prevention Guide.

Key takeaways

  • Same root cause, different physics. Both flaws mix instructions and data in one channel, but SQL has a parser that can be told which is which, and an LLM only ever predicts the next token.
  • Parameterisation is a guarantee; prompt separation is a hint. A bound value can never be executed as SQL. Delimiters, chat roles and instruction hierarchy make injection less likely but are not, in OWASP's words, "an enforcement boundary".
  • Design for residual risk. The UK NCSC calls LLMs "inherently confusable" and advises reducing the likelihood and impact of prompt injection rather than expecting to eliminate it.
  • The controls that transfer sit outside the model. Least privilege, output handling, authorisation on every tool call and egress restriction work for both flaws because they do not depend on the interpreter behaving.
  • Filters alone fail. Deny-lists and classifiers were the weak answer to SQL injection and are weaker against prompt injection, where attackers can rephrase in any language and a 95 percent catch rate still lets the attack through.

One root cause: code and data in the same channel

SQL injection, described by CWE-89, happens when an application builds a SQL command by concatenating externally influenced input, so characters in that input change the meaning of the command. The database then runs whatever valid SQL results. Prompt injection, described by CWE-1427 "Improper Neutralization of Input Used for LLM Prompting", happens when a product builds a prompt from external data in a way that causes the model "to fail to distinguish between user-supplied inputs" and developer-provided system directives. MITRE places CWE-1427 as a child of CWE-77, the general command injection weakness, alongside the SQL case.

The NCSC's December 2025 analysis puts the shared pattern plainly: prompt injection arises where developers concatenate their own instructions with untrusted content in a single prompt and then treat the output as if a boundary existed between them. It then makes the key point: current LLMs "simply do not enforce a security boundary between instructions and data inside a prompt".

The untrusted channel is also wider: a prompt injection can arrive in anything the model reads, from a web page or email to a tool description or retrieved document. ATT&CK v20 separates the two routes as T1699 Direct Prompt Injection and T1698 Indirect Prompt Injection, and MITRE ATLAS records them as AML.T0051.000 and AML.T0051.001.

Side-by-side comparison

AspectSQL injectionPrompt injection
InterpreterDatabase engine with a formal grammarLanguage model with no grammar distinguishing instruction from content
WeaknessCWE-89CWE-1427 (child of CWE-77)
Where untrusted input entersRequest parameters, headers, stored values reused in later queriesUser prompts and any content the model reads: documents, web pages, email, tool output, memory
Root fixParameterised queries: values sent separately and never parsed as SQLNone at the model level; risk reduced by architecture and deterministic controls around the model
Can the fix be proven?Yes, by code review and testing that every value is boundOnly for designs that keep untrusted text away from consequential actions (for example, the patterns below)
Typical impactRead, change or delete database data; sometimes command execution through database featuresData exfiltration, unauthorised tool actions, misleading output, actions taken with the user's or agent's privileges
Role of filteringSecondary; input validation supports bindingUseful to raise attacker cost; never a boundary
Detection signalSyntax errors, unusual catalogue queries, timing outliersUnexpected tool calls, denied actions, outbound URLs in output, content that mentions instructions
Framework IDsATT&CK T1190 (when exploited in a public-facing application)ATT&CK T1698, T1699; ATLAS AML.T0051; OWASP LLM01:2025

Why parameterisation works for SQL

A parameterised query fixes the SQL text before any user input is involved. The database parses that text once, builds a plan, and receives values separately as bind variables. OWASP's Query Parameterization Cheat Sheet states that "SQL Injection is best prevented through the use of parameterized queries" and explains that bind variables "tell the database that the inputs to this dynamic SQL are 'data' and not possibly code." Whatever characters arrive in a value, the parser never sees them as SQL tokens; the NCSC describes this as the engine being unable ever to interpret the input as an instruction.

Three properties make this a real security control:

  • A formal grammar: SQL has a defined syntax, so "instruction" and "value" are positions the parser can tell apart with certainty.
  • A separate channel: the driver sends the statement and the values through different fields of the protocol, so the separation does not depend on escaping characters correctly.
  • Verifiability: a reviewer or static analysis tool can confirm that every query is built from constants plus bound values. The remaining gaps are known and finite: identifiers such as table and column names, dynamic SQL inside stored procedures, and string-built ORM queries, all covered in the SQL Injection Prevention Guide.

Why there is no LLM equivalent

An LLM receives one sequence of tokens. System prompt, user message, retrieved document and tool output all end up in the same context window, and the model's only operation is to predict the next token from everything it has seen. The NCSC notes that under the hood there is "only ever 'next token'". There is no parser that treats one region as executable and another as inert, so there is nothing to bind a value to.

The techniques that look like parameterisation each fall short in a specific way:

TechniqueWhat it doesWhy it is not a boundary
Delimiters and XML tags around untrusted textLabels content as data for the modelThe model reads the label as more text; OWASP says not to treat text labels or prompt wording as an enforcement boundary
Chat roles (system, user, tool)Marks the source of each message in the APIRoles become tokens in one context; the model is trained to prefer some, not forced to
Instruction hierarchy trainingModel learns to rank system instructions over othersProbabilistic; reduces success rates without guaranteeing refusal
Spotlighting, datamarking, encodingTransforms untrusted text so the model can recognise its originHelps the model recognise untrusted text; a determined or novel attack can still succeed
Structured outputs and JSON schemasForces the model's output into a defined shapeConstrains the shape of the answer, not the influence of the input on its content; a well-formed call can still carry the attacker's choice of recipient
Classifiers and guardrail modelsDetect likely injection text before or after the modelStatistical, can be evaded by rephrasing, and can themselves be injected

The NCSC calls the LLM an "inherently confusable deputy": a privileged component that can be talked into acting for a less privileged party, where the confusion cannot be engineered out of the component itself. CWE-1427 rates differentiating input in the prompt as only moderately effective. The practical conclusion is that the security boundary has to move from inside the prompt to the code around the model.

Controls that transfer and controls that do not

SQL injection controlPrompt injection analogueTransfers?
Parameterised queriesDelimiters, roles, structured promptsNo: helps, but is not a guarantee
Least privilege database accountAgent and tool credentials scoped to the task and the requesting userYes, fully: limits blast radius regardless of model behaviour
Allowlist for identifiers (table, column, sort order)Action-Selector pattern: model chooses from a fixed set of actions; parameters validated in codeYes, where the use case allows a fixed action set
Output encoding before renderingTreat model output as untrusted: encode HTML, block or rewrite external URLs and images, parameterise any SQL the model writesYes: OWASP LLM05 requires parameterised queries for database operations involving LLM output
No outbound network from the databaseEgress allowlists for agents and rendered outputYes: breaks the exfiltration leg
Web application firewall signaturesPrompt firewalls and injection classifiersPartly: raises cost, misses novel phrasing
Input validation and escapingNormalising text, stripping hidden characters and markupPartly: removes cheap tricks, not semantic attacks
Error suppressionHiding system promptsNo: secrecy is not a control in either case

The pattern is consistent. Controls that act on the interpreter's input (parameterisation, filters) lose their power when the interpreter has no grammar. Controls that act on what the interpreter is allowed to do afterwards (privilege, authorisation, output handling, egress) keep all of it. The NCSC's design principle follows the same line: when an LLM processes information from a party, its privileges should drop to that party's level. See the OWASP LLM Top 10 LLM06 Excessive Agency Guide and the OWASP LLM Top 10 LLM05 Improper Output Handling Guide.

Designing around a model that cannot separate code from data

Because the prompt cannot be made safe, the design goal changes from "keep bad text out" to "make it impossible for bad text to cause harm". A 2025 paper by researchers from IBM, Invariant Labs, ETH Zurich, Google, Microsoft and others states the principle: once an agent has ingested untrusted input, "it must be constrained so that it is impossible for that input to trigger any consequential actions". It proposes six patterns: Action-Selector, Plan-Then-Execute, LLM Map-Reduce, Dual LLM, Code-Then-Execute and Context-Minimization. The CaMeL design goes further, extracting control and data flow from the trusted query so that untrusted data "can never impact the program flow", and using capabilities to block exfiltration; on the AgentDojo benchmark it reported solving 77 percent of tasks with provable security against 84 percent for an undefended system.

A useful screening test is Simon Willison's "lethal trifecta": access to private data, exposure to untrusted content, and the ability to communicate externally. An application with all three is exposed to data theft through prompt injection whatever filters it runs; removing any one leg breaks the exfiltration path. The Prompt Injection Guide covers the patterns in implementation detail.

Threat model, failure modes and decision criteria by option

SQL injection

Threat model. An attacker reaches a query built from their input, usually in a public-facing application (T1190), and changes its meaning to read, alter or delete data, or to reach operating system features through the database.

Failure modes. A single concatenated query in an otherwise parameterised code base; identifiers taken from input; dynamic SQL inside stored procedures; second-order injection from stored values; and an application account with owner rights that turns one flaw into full database compromise.

Controls. Bind every value; allowlist identifiers; static analysis rules that fail builds on string-built queries; one least-privilege account per application; no outbound network from database servers; monitoring for syntax error bursts and catalogue queries.

Decision criteria. Treat SQL injection as a solved class: the question is coverage, not technique. Measure the share of queries that are parameterised and drive it to all of them.

Prompt injection

Threat model. Anyone who can place text where the model will read it can try to steer the model: the user directly, or a third party through email, documents, web pages, tickets or tool output. The impact is whatever the model can do: read data in its context, call tools with its credentials, and send data out through links, images or messages.

Failure modes. Relying on a system prompt instruction to "ignore instructions in documents"; deploying a classifier as the only control; giving an agent one broad service account rather than the requesting user's permissions; rendering model output with external images and links; and allowlists that include domains the organisation no longer owns.

Controls. Scope credentials to the user and task; authorise every tool call in code against the user, data and destination; require human approval for irreversible or external actions; treat model output as untrusted input to every downstream system; restrict egress; separate agents that read untrusted content from agents that hold sensitive tools; log prompts, retrieved sources, tool calls and denials.

Decision criteria. Decide per feature whether the residual risk is acceptable, as the NCSC advises. If the trifecta is present and the actions are consequential, use a structural pattern (Dual LLM, Plan-Then-Execute, Action-Selector) or remove a leg; if the feature has no tools and no private data, input and output screening plus clear user messaging may be proportionate.

Where the two meet: models that write SQL

Text-to-SQL assistants combine both risks. A user or a poisoned document can steer the model into writing harmful SQL, and the model's output then reaches a real interpreter. OWASP LLM05 lists "LLM-generated SQL queries are executed without proper parameterization" as a vulnerability example and requires parameterised queries for all database operations involving LLM output. In practice that means the model should produce structured intent (which report, which filters, which date range) that code turns into a parameterised query from a fixed template, or, where free-form SQL is unavoidable, the query runs under a read-only account restricted to approved views, with row-level security enforcing the requesting user's permissions, statement timeouts and a deny on data-changing statements at the database, not in the prompt.

Worked scenarios

Scenario 1: an analytics assistant over the finance warehouse. A team builds a chat interface that answers questions by writing SQL. Version one passed model-written SQL to the warehouse under a service account that could read every schema, and a tester retrieved another department's salary data. The redesign keeps the model, but changes everything around it: the model now emits a JSON request naming one of 40 approved query templates and its parameters, code validates each parameter against an allowlist and binds it into a parameterised query, and the database session runs as the requesting user with row-level security. The same malicious question now produces either a validation error or a result limited to data the user could already see.

Scenario 2: an email triage agent. A support agent reads inbound email, summarises it, looks up the customer record and can reply. It has all three legs of the trifecta. An injection classifier was bypassed by red-teamers writing instructions in another language. The second design splits the agent: a quarantined model with no tools summarises each email into a fixed schema (intent, order number, sentiment), and a privileged component that never sees raw email text decides actions from that schema. Replies go through a template, external links are stripped from output, and refunds above a set value need human approval. Live cases such as EchoLeak 2025, where a crafted email led an assistant to place data in an image reference, show why the output and egress controls matter as much as the input screening.

Where identity fits

Because the model cannot be trusted to refuse, the identity it acts with is the real control. An agent that runs under one broad service account turns every successful injection into a privilege escalation; an agent that acts with the requesting user's delegated, task-scoped permissions limits the damage to what that user could already do. Treat each agent and tool connector as a non-human identity with an owner, scoped credentials and logged actions. See the AI Agent Authorisation Guide.

Detection and measurement

  • Parameterisation coverage: share of database calls, including those built from LLM output, that use bound parameters or fixed templates. Target all of them.
  • Tool call denial rate: policy denials per thousand agent tool calls, by agent and tool. The NCSC notes failed tool or API calls can reveal the early stages of an attack.
  • Trifecta exposure: number of production LLM features with private data, untrusted input and an external channel all present, and the trend as designs change.
  • Egress blocks: blocked outbound URLs, images or messages from model output, investigated within a set time.
  • Red-team success rate: share of injection test cases that cause an unauthorised action (not merely odd text), measured per release.
  • Log completeness: share of agent sessions with prompt, retrieved sources, tool calls and outputs retained for investigation.

Common failure patterns

  • Calling delimiters "parameterisation". Teams wrap untrusted text in tags, declare the problem solved and grant the agent broad tools. The tags lower success rates; they do not stop a determined attack.
  • Filter-only defence. A classifier or deny-list is the only control. The NCSC advises against deny-listing phrases because attacks can be endlessly rephrased, and Willison calls a 95 percent detection rate "very much a failing grade".
  • Trusting the system prompt. Instructions such as "never reveal data" are text the attacker can argue with. Secrets and authorisation rules belong in code.
  • Executing model output. Model-written SQL, shell commands or HTML passed downstream without parameterisation, sandboxing or encoding recreates classic injection one step later.
  • Stale trust lists. In ForcedLeak 2025, text submitted through a public web form steered a CRM agent, and data left through an image request to an expired domain still on an allowlist; the lessons were scoped agent access, blocked unneeded output channels and reviewed allowlists.
  • One identity for all users. An agent with a shared high-privilege account lets any injected instruction act beyond the requesting user's rights.

Framework mapping

FrameworkReferenceRelevance
OWASP Top 10 for LLM Applications 2025LLM01, LLM05, LLM06Prompt injection; improper output handling (including parameterising LLM-generated SQL); excessive agency
CWECWE-89, CWE-1427, CWE-77SQL injection; LLM prompt neutralisation; parent command injection weakness
MITRE ATT&CK v20 and ATLAST1190, T1698, T1699, AML.T0051Exploit public-facing application; indirect and direct prompt injection; LLM prompt injection
NIST SP 800-53 Rev 5SI-10, SI-15, AC-6, AC-4Input validation; output filtering; least privilege; information flow enforcement (egress)
NIST CSF 2.0PR.PS-06, PR.AA-05, DE.CM-09Secure development practices; least privilege permissions; monitoring runtime environments
ISO/IEC 27001:2022 Annex AA.8.26, A.8.28Application security requirements; secure coding

Practitioner checklist

  • Parameterise every SQL statement, including statements built from LLM output, and fail builds on string-built queries.
  • Record in each LLM feature's risk assessment that prompt injection is a residual risk and who accepted it.
  • Map every LLM feature against the lethal trifecta and remove a leg where actions are consequential.
  • Run agents and tools with the requesting user's scoped permissions, never a shared broad account.
  • Authorise every tool call in code against user, data and destination, with human approval for irreversible or external actions.
  • Treat model output as untrusted: encode it, strip or rewrite external URLs and images, and validate structured output before use.
  • Use delimiters, spotlighting and classifiers to raise attacker cost, and document that they are not boundaries.
  • Restrict egress for agents and rendered output to an allowlist, and review that allowlist for expired domains.
  • Log prompts, retrieved sources, tool calls, denials and outputs, and alert on denied or unusual tool calls.
  • Red-team each release for unauthorised actions, not just unwanted text.

Standards and references

Related NHI Mgmt Group resources: Prompt Injection Guide · SQL Injection Prevention Guide · Prompt Injection vs Jailbreaking · Adversarial Examples vs Prompt Injection · Structured Outputs vs Free Text for Agent Actions

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

NHIMG Editorial Note
Researched and written by the NHI Mgmt Group editorial team using AI tools, under the editorial direction of Lalit Choda. Facts are drawn from the sources listed on this page and checked by our automated quality process. Last updated 14 November 2026. Spotted an error? Use our contact page.
NHI Mgmt Group, the independent authority on Non-Human Identity, IAM and Agentic AI security. nhimg.org