SQL injection: how it works, how to test for it and how to fix it
SQL injection is what happens when text someone typed into your website becomes part of a command to your database.
This guide explains it in plain English, then gives you a lab to run on your own machine with Node.js alone: one lookup built two ways, the evidence from each request, and a regression test that fails until the fix is in.
In this guide
SQL injection lab: one lookup built two ways, with a regression test
An illustration, not a client system: an invented equipment hire business with four invented bookings in an in-memory SQLite database. Three files run with Node.js alone. lab.mjs sends three searches to a concatenated and a parameterised version of the same lookup and prints what was sent, the SQL text and values the database received, and the response. regression.test.mjs fails on the concatenated version and passes on the parameterised one.
How to use itHide the instructions
The same fix follows in Prisma, Drizzle and the Supabase client. Run it on your own machine, for learning and for testing code you own.
sql-injection.txt
ILLUSTRATION ONLY. The equipment hire business, its customers and its bookings are invented. The database lives in memory on your own machine and disappears when the process ends. Use this lab for learning and for testing code you own.
Needs: Node.js 22.13.0 or later, or 23.4.0 or later on the 23 line. Nothing to install: the lab uses node:sqlite, node:http, node:test and node:assert, which ship with Node.js.
Written and run on: Node.js 26.0.0. Every output below comes from that run. Test timings will differ on your machine.
Setup: make an empty folder, save the three files below into it with the names shown, and open a terminal in that folder.
================================================================
FILE 1 OF 3: bookings.mjs
================================================================
// bookings.mjs: the database and the two ways of building one query.
// Illustration only: an invented equipment hire business with invented rows.
// The database lives in memory and disappears when the process exits.
import { DatabaseSync } from 'node:sqlite'
// The lab treats every request as coming from this signed-in customer.
export const SIGNED_IN_CUSTOMER = 'CUST-A'
export function createBookingsDatabase() {
const database = new DatabaseSync(':memory:')
database.exec(
'CREATE TABLE bookings (id INTEGER PRIMARY KEY, customer_id TEXT NOT NULL, site_name TEXT NOT NULL)'
)
const insert = database.prepare('INSERT INTO bookings (id, customer_id, site_name) VALUES (?, ?, ?)')
insert.run(1, 'CUST-A', 'Main St Depot')
insert.run(2, 'CUST-A', "O'Brien Farm")
insert.run(3, 'CUST-B', 'Riverside Units')
insert.run(4, 'CUST-C', 'Hillview School')
return database
}
// VULNERABLE: the visitor's text is joined into the SQL text.
export function buildConcatenatedQuery(customerId, siteName) {
const sql =
"SELECT id, customer_id, site_name FROM bookings WHERE customer_id = '" +
customerId +
"' AND site_name = '" +
siteName +
"'"
return { sql: sql, values: [] }
}
// FIXED: the SQL text never changes, and the values travel separately.
export function buildParameterisedQuery(customerId, siteName) {
const sql = 'SELECT id, customer_id, site_name FROM bookings WHERE customer_id = ? AND site_name = ?'
return { sql: sql, values: [customerId, siteName] }
}
// Both versions run through prepare(). Preparing a string that already
// contains the visitor's text does not protect it.
export function runQuery(database, query) {
const statement = database.prepare(query.sql)
return statement.all(...query.values)
}
================================================================
FILE 2 OF 3: lab.mjs
================================================================
// lab.mjs: a local web server with both versions of the lookup, and the
// requests that show the difference. It listens on 127.0.0.1 only.
import { createServer } from 'node:http'
import {
SIGNED_IN_CUSTOMER,
buildConcatenatedQuery,
buildParameterisedQuery,
createBookingsDatabase,
runQuery,
} from './bookings.mjs'
const database = createBookingsDatabase()
const builders = { concatenated: buildConcatenatedQuery, parameterised: buildParameterisedQuery }
function sendJson(response, status, body) {
response.writeHead(status, { 'content-type': 'application/json' })
response.end(JSON.stringify(body))
}
function handleRequest(request, response) {
const url = new URL(request.url, 'http://127.0.0.1')
const buildQuery = builders[url.pathname.split('/')[1]]
if (!buildQuery) return sendJson(response, 404, { error: 'Not found' })
const query = buildQuery(SIGNED_IN_CUSTOMER, url.searchParams.get('site') || '')
console.log(' SQL text sent to the database: ' + query.sql)
console.log(' Values sent separately: ' + JSON.stringify(query.values))
try {
sendJson(response, 200, { bookings: runQuery(database, query) })
} catch (error) {
console.log(' Database error (server log only): ' + error.message)
sendJson(response, 500, { error: 'Lookup failed' })
}
}
const requests = [
['R1', 'Main St Depot'],
['R2', "O'Brien Farm"],
['R3', "zz' OR 'a'='a"],
]
async function sendRequest(port, label, version, siteName) {
const path = '/' + version + '/bookings?site=' + encodeURIComponent(siteName)
console.log(label + ' ' + version)
console.log(' Request: GET ' + path)
const response = await fetch('http://127.0.0.1:' + port + path)
console.log(' Response: ' + response.status + ' ' + (await response.text()))
}
const server = createServer(handleRequest)
server.listen(0, '127.0.0.1', async () => {
const port = server.address().port
for (const [label, siteName] of requests) {
await sendRequest(port, label, 'concatenated', siteName)
await sendRequest(port, label, 'parameterised', siteName)
}
server.close()
})
================================================================
FILE 3 OF 3: regression.test.mjs
================================================================
// regression.test.mjs: fails while a tautology can widen the lookup.
// Run: node regression.test.mjs concatenated (expect failures)
// node regression.test.mjs parameterised (expect every test to pass)
// With no argument it tests the parameterised version, which is what
// node --test runs in a pipeline.
import assert from 'node:assert/strict'
import { test } from 'node:test'
import {
SIGNED_IN_CUSTOMER,
buildConcatenatedQuery,
buildParameterisedQuery,
createBookingsDatabase,
runQuery,
} from './bookings.mjs'
const builders = { concatenated: buildConcatenatedQuery, parameterised: buildParameterisedQuery }
const version = process.argv[2] || 'parameterised'
const buildQuery = builders[version]
if (!buildQuery) throw new Error('Unknown version: ' + version)
const database = createBookingsDatabase()
function findBookingIds(siteName) {
const rows = runQuery(database, buildQuery(SIGNED_IN_CUSTOMER, siteName))
return rows.map((row) => row.id)
}
test(version + ': an exact site name returns that booking only', () => {
assert.deepEqual(findBookingIds('Main St Depot'), [1])
})
test(version + ': an apostrophe in a site name is treated as data', () => {
assert.deepEqual(findBookingIds("O'Brien Farm"), [2])
})
const tautologyInputs = ["zz' OR 'a'='a", "zz' OR '1'='1"]
for (const input of tautologyInputs) {
test(version + ': tautology input returns no bookings: ' + input, () => {
assert.deepEqual(findBookingIds(input), [])
})
}
================================================================
STEP 1: send the requests
================================================================
Command: node lab.mjs
R1 concatenated
Request: GET /concatenated/bookings?site=Main%20St%20Depot
SQL text sent to the database: SELECT id, customer_id, site_name FROM bookings WHERE customer_id = 'CUST-A' AND site_name = 'Main St Depot'
Values sent separately: []
Response: 200 {"bookings":[{"id":1,"customer_id":"CUST-A","site_name":"Main St Depot"}]}
R1 parameterised
Request: GET /parameterised/bookings?site=Main%20St%20Depot
SQL text sent to the database: SELECT id, customer_id, site_name FROM bookings WHERE customer_id = ? AND site_name = ?
Values sent separately: ["CUST-A","Main St Depot"]
Response: 200 {"bookings":[{"id":1,"customer_id":"CUST-A","site_name":"Main St Depot"}]}
R2 concatenated
Request: GET /concatenated/bookings?site=O'Brien%20Farm
SQL text sent to the database: SELECT id, customer_id, site_name FROM bookings WHERE customer_id = 'CUST-A' AND site_name = 'O'Brien Farm'
Values sent separately: []
Database error (server log only): near "Brien": syntax error
Response: 500 {"error":"Lookup failed"}
R2 parameterised
Request: GET /parameterised/bookings?site=O'Brien%20Farm
SQL text sent to the database: SELECT id, customer_id, site_name FROM bookings WHERE customer_id = ? AND site_name = ?
Values sent separately: ["CUST-A","O'Brien Farm"]
Response: 200 {"bookings":[{"id":2,"customer_id":"CUST-A","site_name":"O'Brien Farm"}]}
R3 concatenated
Request: GET /concatenated/bookings?site=zz'%20OR%20'a'%3D'a
SQL text sent to the database: SELECT id, customer_id, site_name FROM bookings WHERE customer_id = 'CUST-A' AND site_name = 'zz' OR 'a'='a'
Values sent separately: []
Response: 200 {"bookings":[{"id":1,"customer_id":"CUST-A","site_name":"Main St Depot"},{"id":2,"customer_id":"CUST-A","site_name":"O'Brien Farm"},{"id":3,"customer_id":"CUST-B","site_name":"Riverside Units"},{"id":4,"customer_id":"CUST-C","site_name":"Hillview School"}]}
R3 parameterised
Request: GET /parameterised/bookings?site=zz'%20OR%20'a'%3D'a
SQL text sent to the database: SELECT id, customer_id, site_name FROM bookings WHERE customer_id = ? AND site_name = ?
Values sent separately: ["CUST-A","zz' OR 'a'='a"]
Response: 200 {"bookings":[]}
Reading the evidence:
R1 An ordinary site name. Both versions return booking 1 and nothing else.
R2 A real site name with an apostrophe. The concatenated version sends broken SQL, SQLite rejects it and the visitor gets a 500. The parameterised version sends the same SQL text as in R1 and returns booking 2.
R3 A tautology. In the concatenated version the input becomes part of the WHERE clause, and the response holds all four bookings, including those of CUST-B and CUST-C. In the parameterised version the SQL text does not change, the input is only a value to match, no site has that name, and the list comes back empty.
================================================================
STEP 2: run the regression test against the concatenated version
================================================================
Command: node regression.test.mjs concatenated
✔ concatenated: an exact site name returns that booking only (1.399333ms)
✖ concatenated: an apostrophe in a site name is treated as data (0.145917ms)
✖ concatenated: tautology input returns no bookings: zz' OR 'a'='a (1.096875ms)
✖ concatenated: tautology input returns no bookings: zz' OR '1'='1 (0.1285ms)
ℹ tests 4
ℹ suites 0
ℹ pass 1
ℹ fail 3
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 6.906375
✖ failing tests:
test at regression.test.mjs:32:1
✖ concatenated: an apostrophe in a site name is treated as data (0.145917ms)
Error: near "Brien": syntax error
(stack trace lines removed here)
test at regression.test.mjs:39:3
✖ concatenated: tautology input returns no bookings: zz' OR 'a'='a (1.096875ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
+ actual - expected
+ [
+ 1,
+ 2,
+ 3,
+ 4
+ ]
- []
(stack trace lines removed here; the second tautology case fails the same way)
The process exits with code 1, so a pipeline step that runs this test fails.
================================================================
STEP 3: run it against the parameterised version
================================================================
Command: node regression.test.mjs parameterised
✔ parameterised: an exact site name returns that booking only (1.189209ms)
✔ parameterised: an apostrophe in a site name is treated as data (0.070042ms)
✔ parameterised: tautology input returns no bookings: zz' OR 'a'='a (0.061166ms)
✔ parameterised: tautology input returns no bookings: zz' OR '1'='1 (0.043709ms)
ℹ tests 4
ℹ suites 0
ℹ pass 4
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 5.164708
The process exits with code 0. With no argument the file tests the parameterised version, so node --test finds it in a pipeline by its .test.mjs name.
================================================================
STEP 4: the same fix in an ORM or query builder
================================================================
Not run in this lab. Each snippet follows the method chain its project's documentation shows, and assumes a bookings table or model with customer and site columns. The signed-in customer comes from your session, not from the request.
Prisma ORM (a where object passed to findMany, as on Prisma's filtering and sorting page):
const bookings = await prisma.booking.findMany({
where: { customerId: session.customerId, siteName: siteName },
})
Drizzle ORM (and() combining eq() filters, as on Drizzle's select page):
import { and, eq } from 'drizzle-orm'
const rows = await db
.select()
.from(bookings)
.where(and(eq(bookings.customerId, session.customerId), eq(bookings.siteName, siteName)))
Supabase JavaScript client (from(), select() and eq(), as in Supabase's eq() reference):
const { data, error } = await supabase
.from('bookings')
.select('id, site_name')
.eq('site_name', siteName)
Here a row level security policy on bookings limits rows to the signed-in user, for example by comparing (select auth.uid()) with a user_id column as Supabase's example policies do. The query itself does not filter by customer.
Escape hatches to search your own code for:
Prisma: $queryRawUnsafe, $executeRawUnsafe, Prisma.raw
Drizzle: sql.raw(
Supabase client: .or( and .filter( with a string built from input
node:sqlite, node-postgres and other drivers: SQL text built with + or with an untagged template literal before it reaches prepare(), exec() or query()
================================================================
STEP 5: point the test at your own code
================================================================
1. Copy regression.test.mjs into your project's tests.
2. Change findBookingIds to call your real data access function as a seeded test customer, against a test database that holds rows for at least two customers.
3. Keep the ordinary case, the apostrophe case and both tautology cases. Add a tautology case for each other text input that reaches a query: search, filters, sort options, and any stored field a later report reads back.
4. Run it in the pipeline that deploys your app. A failure on the apostrophe case means text is joined into SQL, or validation is rejecting real names. A failure on a tautology case means input can widen the lookup beyond the signed-in customer's rows.What SQL injection is
A website that keeps bookings, orders or customer accounts in a SQL database, such as PostgreSQL, MySQL or SQLite, asks for them in a language called SQL.
A lookup such as "show this customer's bookings at this site" becomes a short SQL command. SQL injection happens when the application builds that command by pasting in text a visitor supplied, and the text contains characters SQL reads as part of the command rather than as data.
OWASP's SQL Injection Prevention Cheat Sheet puts it in one sentence: a SQL injection attack occurs when untrusted data becomes part of a query's SQL syntax, modifying the logic of the SQL request.
MITRE catalogues the weakness as CWE-89, Improper Neutralization of Special Elements used in an SQL Command, and lists SQL injection and SQLi as alternate terms. Its description says the product builds all or part of an SQL command from externally influenced input but does not neutralise, or incorrectly neutralises, special elements that could change the intended command, so the generated query can treat that input as SQL instead of ordinary user data.
The OWASP Top 10:2025 maps CWE-89 to its A05 Injection category, where it describes SQL injection as low frequency and high impact.
How much damage a successful injection does depends on the database and on the account the application connects with. The cheat sheet says it can, depending on database features and privileges, read data, change it through inserts, updates and deletes, run administration operations such as shutting the database down, read or write files on the database server and, in some cases, run operating system commands.
CWE-89 adds that where SQL built this way checks user names and passwords, it may be possible to sign in as another user without knowing the password.
In business terms: when your developer's instructions and your customer's words reach the database as one joined-up string, the database has no way to tell which part was which. The fix is to send them separately. The rest of this page shows that fix running, where it stops, and how to check your own site, whether it runs on Next.js, WordPress or Supabase.
NoSQL databases such as MongoDB have injection problems of their own, with different syntax and different fixes, and they have their own guide in this library. This page is about SQL databases and the hosted services built on them.
A SQL injection example, step by step
The lab on this page uses one invented business so each step can be shown with real output.
An equipment hire company lets signed-in customers look up their bookings by job site. The customer comes from the session, the site name comes from a search box, and the vulnerable version joins both into the SQL text with plus signs. Three searches show what that does.
- Main St Depot, an ordinary search. The database receives SELECT id, customer_id, site_name FROM bookings WHERE customer_id = 'CUST-A' AND site_name = 'Main St Depot' and returns the one matching booking. Nothing looks wrong.
- O'Brien Farm, a real site with an apostrophe in its name. The apostrophe ends the quoted text early, the database finds a stray word, Brien, and SQLite rejects the query with a syntax error. No attacker is involved: a real customer's real site name produces an error page.
- zz' OR 'a'='a, typed on purpose. The first apostrophe closes the quoted text and the rest adds a condition of its own, so the WHERE clause reads customer_id = 'CUST-A' AND site_name = 'zz' OR 'a'='a'. The response holds all four bookings in the table, including two that belong to other customers.
Why the third search returns everything
The third input is a tautology: a condition that is always true. CWE-89's worked example uses the same form, name' OR 'a'='a, against a query restricted to the signed-in owner, and explains that the added condition makes the WHERE clause always evaluate to true, so the query returns every entry in the table regardless of owner.
The summary of OWASP's SQL injection test, WSTG-INPV-05, shows the same idea with the input 10 or 1=1.
A tautology makes a good test marker on your own systems because its evidence is plain, rows that should not come back, and the query only reads.
Two details are worth carrying away. The apostrophe is an early signal: CWE-89 notes that its example query only behaves correctly if the input contains no single quote, and that a surname such as O'Reilly would likely pass a validation step yet cannot go into such a query directly.
And the damage in the third search came from a read-only search box. Nothing was deleted. Another customer's data was handed to whoever asked.
SQL injection prevention: parameterised queries and why they work
The fix is to stop building the command out of the visitor's text.
A parameterised query sends the database two things separately: SQL text with placeholders where the values belong, and the values themselves. The lab's fixed version sends SELECT id, customer_id, site_name FROM bookings WHERE customer_id = ? AND site_name = ? and, alongside it, the customer ID and the site name. The SQL text is the same on every request, whatever the visitor typed.
OWASP's cheat sheet gives the resolution as defining the SQL structure separately from its data values, then binding those values through the database API. For an input like tom' or '1'='1 it gives the result: the input is treated as the literal username to match, not as a condition added to the query.
The lab shows the same thing. The tautology becomes a search for a site literally named zz' OR 'a'='a, no site has that name, and the response is an empty list, while O'Brien Farm comes back correctly.
Database drivers document the same behaviour for their own APIs. The node-postgres documentation warns that concatenating parameters into the query text can (and often does) lead to SQL injection, and says its parameterised queries pass the query text unaltered, with the parameters, to the PostgreSQL server, which substitutes them itself.
Node.js documents for its built-in SQLite module that parameters offer protection against SQL injection attacks, and that prepared statements are preferred over hand-crafted SQL strings when handling user input.
Calling a function named prepare() is not the same thing. The lab's vulnerable version also goes through prepare(), on a string that already contains the visitor's text, and the cheat sheet says concatenating untrusted values into the query before preparing it defeats the protection.
In JavaScript the gap can be a single word. Node.js's documentation shows a tagged template literal, where each embedded value is bound as a parameter, beside the same literal without the tag, which it marks as unsafe because the value is interpolated into the query text as a string and can lead to SQL injection and data corruption.
Two older habits fall short. Escaping the visitor's text into the SQL string yourself is what the cheat sheet calls error-prone and strongly discourages, because escaping rules differ between SQL dialects and some database configuration, such as MySQL's NO_BACKSLASH_ESCAPES, might affect them.
Input validation is worth having, but the cheat sheet says it complements parameter binding and does not replace it: a value that passes type, length or format checks still should not be concatenated into SQL.
If you work to a standard, ASVS 5.0 requirement 1.2.4, at Level 1, asks that database queries use parameterised queries, ORMs or entity frameworks, or are otherwise protected from SQL injection and other database injection attacks, and notes that this is also relevant when writing stored procedures.
Running the lab on your own machine
The lab is an illustration: an invented equipment hire business with four invented bookings, in a SQLite database that lives in memory and disappears when the process ends.
It is three files and uses only modules that ship with Node.js, including its built-in SQLite module, so there is nothing to install. It is for learning and for testing code you own. Testing a system you do not own, without the owner's written authority, is not something this page helps with.
It was written and run on Node.js 26.0.0, and every output in it comes from that run; test timings will differ on your machine. The Node.js documentation lists its SQLite module as no longer behind a flag from versions 22.13.0 and 23.4.0, so use one of those or later, and marks the module a release candidate from 25.7.0.
Current documentation names the database class Database and keeps DatabaseSync, the name the lab uses, as a deprecated alias for backward compatibility.
- Make an empty folder, save the three files into it with the names shown, and open a terminal there.
- Run node lab.mjs. It starts a web server on 127.0.0.1 on a free port, sends the three searches to both versions, and prints, for each request, what was sent, the SQL text and values the database received, and the response. Then it stops.
- Run node regression.test.mjs concatenated. Three of its four tests fail: the apostrophe causes a syntax error, and both tautology inputs return all four bookings.
- Run node regression.test.mjs parameterised. All four pass. With no argument the file tests the parameterised version, so node --test, which by default runs files whose names end in .test.mjs, can run it in a pipeline, and a failing test sets the process exit code to 1.
Pointing the regression test at your own code
Keep the test's cases and change one function. findBookingIds should call your real data access function as a seeded test customer, against a test database that holds rows for at least two customers. The ordinary search checks that the lookup still works.
The apostrophe case catches two different faults: text joined into SQL, and validation so strict it rejects real names. Each tautology case fails if input can widen a lookup beyond the signed-in customer's rows.
ORM SQL injection: where query builders still let it in
ASVS 1.2.4 lists ORMs and entity frameworks beside parameterised queries, and Prisma's documentation says the ideal way to avoid SQL injection in Prisma Client is to use the ORM models to perform queries wherever possible.
The lab shows the booking lookup in Prisma, Drizzle and the Supabase client, each following the method chain its own documentation shows.
Injection comes back through the escape hatches these tools offer for raw SQL and raw filters. OWASP's Top 10:2025 lists unsanitised data used within ORM search parameters to extract additional, sensitive records among the conditions that make an application vulnerable to injection. These are the places to search your code.
- Prisma: $queryRawUnsafe and $executeRawUnsafe, which Prisma's documentation says are at significant risk of making code vulnerable to SQL injection. Its tagged-template methods, $queryRaw and $executeRaw, create prepared statements, but the same page shows them made vulnerable by passing user input through Prisma.raw, or by building a fake tagged template from a concatenated string.
- Drizzle: sql.raw(). Drizzle's documentation says its sql template maps tables and columns to escaped names and moves dynamic values into an array passed separately to the database, while sql.raw() includes raw SQL without any additional processing or escaping.
- Supabase client: or() and filter(). The reference says each takes raw PostgREST syntax that is used as-is and needs to be properly sanitised, and calls filter() an escape hatch, advising the specific filter methods wherever possible.
- Drivers such as node-postgres and Node.js's SQLite module: any SQL text built with a plus sign or an untagged template literal before it reaches query(), prepare() or exec().
- Hibernate and JPA, for Java teams: the cheat sheet notes that ORMs with their own query languages, HQL and JPQL, may suffer from the same injection problems, and that parameterised queries are the recommended solution there as well. Its HQL example uses named parameters.
When a raw query is the right tool
Sometimes it is: a report the ORM cannot express, or a database feature it does not cover. Keep the SQL text a constant in your code, put every value in a placeholder, and give the function a regression test like the lab's, so the next person to edit it finds out straight away if a value slips into the text.
What parameterised queries do not fix
Parameters close the gap they were built for.
Four related gaps stay open, and each needs its own control.
Placeholders stand in for values only. The cheat sheet says parameter markers represent data values, not table names, column names or SQL keywords such as ASC and DESC, and ASVS 5.0 notes that query parts such as table and column names, including ORDER BY column names, cannot be escaped. node-postgres says PostgreSQL does not support parameters for identifiers, and Prisma's documentation says a table or column name cannot be passed as a variable into a parameterised query.
The control is an allow-list in code. A sort option arrives as a short word such as latest or cheapest, your code maps each word to a column and direction it already holds, and anything else is rejected or replaced with the default.
That is the cheat sheet's instruction: map the selection to a small set of application-owned values allowed for that query, reject anything else, and turn a requested sort direction into the literal ASC or DESC rather than appending the text supplied.
Quoting tools for identifiers, such as PostgreSQL's format() with %I or WordPress's %i placeholder, keep the syntax intact, but the cheat sheet points out that identifier quoting does not restrict which tables the application may select. The mapping stays the control.
Moving a query into a stored procedure or a database function does not help if the procedure builds SQL from its arguments. The cheat sheet says binding procedure arguments protects the call, not dynamic SQL constructed inside the procedure.
OWASP's Top 10:2025 adds that even when parameterised, stored procedures can still introduce SQL injection if the PL/SQL or T-SQL in them concatenates queries and data or executes hostile data with EXECUTE IMMEDIATE or exec().
WSTG-INPV-05 gives the example of a reporting procedure where the user selects the columns to view, and warns that the user could insert malicious code into that scenario and compromise the data.
PostgreSQL, the database behind Supabase's database functions, documents the safer form. Values go into a dynamic command through EXECUTE with a USING clause, which its documentation says is much less prone to SQL injection because there is no need for quoting or escaping. Parameter symbols can only stand for data values, so a table or column name goes in through quote_ident() or format() with %I, and the allow-list above still decides which names are allowed.
CWE-89 states the general rule: do not dynamically construct and execute query strings inside these features with exec or similar functionality.
A bound parameter decides what the SQL means. It does not decide who may run it. The cheat sheet says parameter binding prevents a value from changing SQL syntax but does not decide whether the caller may access the matching account.
In the lab, the fixed version holds against the tautology partly because the customer ID comes from the session. If it came from the request, a visitor could change it to another customer's ID and read their bookings without any SQL injection at all, which the cheat sheet describes as changing a parameter from one of the legal values presented to a value that is unauthorised for them.
Data does not become trustworthy by being stored. The cheat sheet lists the database itself among the sources of malicious data, and says its controls apply whether data comes from an HTTP request, another service or previously stored data.
A customer name saved through a parameterised insert can still break a nightly report that later joins it into SQL text, so the report query needs the same treatment as the form.
Least-privilege database accounts limit the damage
Parameters prevent the injection; the database account decides how far a missed one can reach.
OWASP's cheat sheet asks you to minimise the privileges of every database account, starting from what each application account needs rather than working out what to take away. An account that only reads should be granted read access only to the tables it needs, and an application account should not be given DBA or admin access.
Its example is a login page, which needs read access to the username and password fields but no write access, beside a sign-up page, which needs to insert: separate database users are what make that difference enforceable.
Views narrow access further. The cheat sheet's example is a product catalogue view that exposes names and retail prices but not supplier costs, with SELECT granted on the view and not on the table beneath it, and it reminds you that queries against views still need parameters.
CWE-89 adds that where a user can read and modify their own data, the database privileges should stop them reading or writing anyone else's. ASVS 5.0 requirement 13.2.2, at Level 2, asks that communication between backend components, including data layers, uses accounts with the least necessary privileges.
On a hosted database the account question becomes a key question. Supabase documents that its secret key works through the service_role Postgres role, bypasses row level security when the request carries no user access token, and must never be used in the browser. Server code that queries with that key gets no help from your row level security policies if one of its queries is injectable.
What to check in a Next.js or Node.js application
Next.js's data security guide says to always validate input from the client because it can be easily modified, and names form data, URL parameters, headers and searchParams.
Its audit checklist adds that route folders with brackets are user input, and the guide says an exported Server Action is reachable by a direct POST request, not only through your interface. Any of these can reach a query, and the same goes for the request data an Express or other Node.js server handles.
- List every query. In a Next.js app that means the Data Access Layer, if you have one, plus each Server Action, route handler and server component that touches the database. The guide's audit checklist asks you to verify that database packages are not imported outside the Data Access Layer, and keeping them inside it makes this list shorter.
- Search for raw query paths: $queryRawUnsafe, $executeRawUnsafe and Prisma.raw in Prisma; sql.raw( in Drizzle; and calls to query(), prepare() or exec() whose SQL text is built with a plus sign or an untagged template literal.
- Check sorting and filtering separately. A sort column, direction or table name taken from searchParams needs the allow-list mapping, whichever library runs the query, because identifiers cannot be bound as parameters.
- Keep database errors in the server log. CWE-89 notes that error messages revealing the structure of a SQL query can help attackers tailor their input, which is why the lab answers Lookup failed and logs the SQLite message on the server only.
- Check the connection. Note which database user each environment connects as and what it is granted. An application that connects as the database owner hands a missed injection everything the owner can do.
- Give each lookup that takes text from a visitor a regression test like the lab's, and run it in the pipeline that deploys the app.
What to check in a WordPress site with custom code or plugins
Theme and plugin code can query the WordPress database directly through the $wpdb object.
The wpdb class reference warns that all untrusted values in an SQL statement must be escaped to prevent SQL injection attacks, that some of its methods escape SQL for you and others do not, and that you should check the documentation before using any of them. Its insert(), update() and replace() methods take column and value pairs raw, with neither side SQL escaped beforehand.
For a query that includes values, the method is $wpdb->prepare(). The reference describes it as preparing a SQL query for safe execution with sprintf()-like placeholders: %d for integers, %f for floats, %s for strings and, since WordPress 6.2.0, %i for identifiers such as table and field names.
Every placeholder is left unquoted and needs a matching argument, and a LIKE wildcard goes inside the argument rather than into the query. The prepared string is then passed to the method that runs it, such as query() or get_col().
- Calls to $wpdb->query(), get_results(), get_row(), get_var() or get_col() whose SQL includes a variable that did not go through prepare(), above all anything taken from $_GET, $_POST or $_REQUEST.
- Placeholders wrapped in quotes in the query string. The prepare() reference says placeholders must be left unquoted.
- Numbered or formatted placeholders, such as %5s. The reference says these do not have quotes added, for compatibility with old behaviour, so the code has to supply the quotes itself. Prefer the plain placeholders.
- An array of values built straight from the request. The class reference says care must be taken not to allow direct user input to that parameter, which would enable array manipulation of any query with multiple placeholders.
- Table or column names from the request. %i quotes an identifier; it does not decide which identifiers are allowed, so map the choice through an allow-list first.
- Entry points open to logged-out visitors. Ajax actions on the wp_ajax_nopriv_ hooks run for logged-out users, and a custom REST endpoint can use __return_true as its permission callback to accept anyone. Check every query those handlers reach.
Third-party plugins
A flaw inside a third-party plugin is fixed by its author, in an update. On your side, that means keeping plugins updated, removing ones you no longer use, and reporting a suspected flaw to the author rather than editing the plugin's files on the live site.
What to check in a Supabase or other hosted-database application
In a Supabase app the browser can query the database through Supabase's JavaScript client, without a server of your own in between.
The client's specific filters, such as eq(), take a column and a value. or() and filter() are different: the reference says they take raw PostgREST syntax that is used as-is and that you need to make sure is properly sanitised.
A search box whose text is pasted into an or() string can change the filter itself, so build those strings only from values your code controls, or use the specific filter methods.
Row level security decides which rows each signed-in user's requests can reach. Supabase says to enable it on every table in an exposed schema, and that a table in an exposed schema without it is readable and writable by any role with a grant on it. Test it the way the lab tests two customers: sign in as one, ask for the other's rows, and expect nothing back.
Database functions are where SQL can be built again. Supabase's guide says functions live inside your database and are called from your app with rpc(). A function that assembles SQL with EXECUTE needs the USING clause and the %I quoting described above. The guide also sets out how much an injectable function could reach.
It recommends security invoker, the default; it says a security definer function runs with its creator's privileges, and that one created in the Dashboard or by a migration is owned by postgres, which bypasses row level security; and it says any role can call a function by default, including anon, the role for requests with no user session.
Its function privileges section shows how to revoke execute and grant it back only to the roles that need it.
Other hosted databases, such as a managed PostgreSQL or MySQL service your Node.js server connects to, follow the Node.js checks above. The account settings live in the provider's dashboard: check which user the connection string names and what that user is granted, and keep the user your application runs as separate from the one your migrations run as.
How to test for SQL injection in your own application
OWASP's Web Security Testing Guide covers this in WSTG-INPV-05, Testing for SQL Injection.
It has two objectives: to identify SQL injection points, and to assess the severity of the injection and the level of access it can achieve. On your own application the first objective is the useful one. A tautology that returns extra rows proves the point exists, and that is enough to justify the fix.
The guide starts by working out where the application talks to a database, giving sign-in forms, search and online shops as examples. The tester then lists every input whose value could be used in a SQL query, including hidden fields in POST requests, HTTP headers and cookies, and tests each one separately so that only one value changes at a time.
The guide says the very first test usually consists of adding a single quote or a semicolon to the field: if the application does not filter it, the quote leads to an incorrect query and the semicolon is likely to generate an error.
- Work on a staging or local copy with synthetic records for at least two customers, not on production data.
- For each input, send an ordinary value, a value with an apostrophe such as O'Brien, and a tautology such as zz' OR 'a'='a. Record the status code, the number of records returned and the query text from your application or database log.
- Read the results the way the lab does. An error on the apostrophe, or more records for the tautology than for a nonsense value, means the input reached the SQL text.
- Stop at that point. The finding is that input changes how the query reads; the fix and a regression test come next, and nothing is gained by pushing further on a system that matters.
- Read the code as well as sending requests. OWASP's Top 10:2025 says injection detection is best achieved by combining source code review with automated testing, including fuzzing, of all parameters, headers, URL, cookies, JSON, SOAP and XML inputs. CWE-89 notes that static analysis can miss custom functions or third-party libraries that run SQL indirectly.
Where a web application firewall fits
A web application firewall can buy time while code is fixed. CWE-89 lists one as a mitigation where code cannot be fixed or as an emergency measure, rates its effectiveness as moderate, and warns that it might not cover all possible input vectors and that some attack techniques might bypass it. Treat it as a stopgap in front of the fix.
All of this is for systems you own or are authorised in writing to test. Sending these inputs to someone else's website without that authority is not something this page helps with.
Where an outside security test fits
Your own tests check the lookups you know about.
A security test also looks for the ones you do not. In the Clever Ops web application and API penetration test, search, filter and sort parameters are checked for SQL injection points (WSTG-INPV-05), along with public inputs such as search, enquiry and sign-up fields. Injection is probed first with input that changes how a query reads, never with input that deletes or overwrites data.
Read-only code access adds depth. With it in scope, queries are read for SQL built from strings instead of parameterised queries (ASVS 5.0 requirement 1.2.4), which reaches raw queries and database functions that requests alone may not show, and a weakness seen in the code is confirmed against a running build where the scope allows.
The report gives each finding with redacted evidence, its business impact, a fix and the criteria the retest will use.
A report is evidence for your decisions, not a certificate. If a tender or contract requires a CREST-accredited provider, Clever Ops is not CREST accredited, so we refer that work to a provider that is. If Clever Ops built or hosts your application, the work is a security review rather than an independent test, and the report says who built it and who hosts it.
Frequently asked questions
It is a way of changing a database command by typing into a website. If an application builds its SQL by pasting in what a visitor typed, the right characters in that text can change what the command does, such as returning other customers' records. CWE-89 describes the result as input being interpreted as SQL instead of ordinary user data.
A booking search that pastes the site name into its SQL. Typing zz' OR 'a'='a closes the quoted text and adds a condition that is true for every row, so the search returns every customer's bookings. The lab on this page shows the request, the SQL the database received and the response, then the same request against the fixed version, which returns nothing.
Its normal query methods are the safer path, and Prisma's documentation calls using its ORM models the ideal way to avoid SQL injection. The raw query methods are where injection returns: Prisma's $queryRawUnsafe and $executeRawUnsafe, Prisma.raw used with user input, and Drizzle's sql.raw(). Sort columns and other identifiers need an allow-list whichever library you use.
No. OWASP's cheat sheet calls relying on escaping error-prone and strongly discourages it, and says input validation complements parameter binding but does not replace it. Validation still earns its place for the things parameters cannot carry, such as a sort column, where an allow-list is the control.
It can block some attempts. CWE-89 rates a firewall's effectiveness as moderate, says it might not cover every input vector and that some attack techniques might bypass it, and suggests one where code cannot be fixed or as an emergency measure. The fix is still a parameterised query in the code.
On a copy you own, list every input that could reach a query, then send each one an ordinary value, a value with an apostrophe and a tautology, one input at a time, and compare status codes, record counts and the logged query text. OWASP's WSTG-INPV-05 describes the core of this method. Test only systems you own or have written authority to test.
Yes, wherever code builds SQL text from input. The OWASP Top 10:2025 maps CWE-89 to A05 Injection, and MITRE lists CWE-89 among the weaknesses in its 2025 CWE Top 25 Most Dangerous Software Weaknesses. Frameworks give you parameterised query methods; the risk sits in raw query methods, procedures that build SQL, and sort and column choices taken from the request.
Scope the right test for your application
Tell us what you have built, who uses it and when it needs to launch. You will get a plain-English recommendation: a website audit, a web application test or a referral to a specialist.