skip to content

parameters, not string glue

type ' OR 1=1 -- into a login form and watch it become code. bound parameters and prepared statements.

address
everything.writes.parameters_and_injection
part
part 5, changing data
chapter
chapter 7 of 10
reading time
10 min

SQL injection is user input that ends up being parsed as SQL. glue a value into a query string and a single quote in it closes your string literal: everything after it is code, written by whoever typed it.

a bound parameter is sent separately, after the query has been parsed, so it can only ever be a value. use parameters for every value. identifiers can't be parameters: quote them with format('%I') and check them against a list.

the picture

you know the login form that looks up a user by email? somewhere behind it is a line like "... WHERE email = '" + email + "'". it works for every email anyone has ever typed. then someone types a quote.

think of a form letter with a blank: "dear ____, your order has shipped." a mail merge fills the blank with a name. now imagine the letter is read aloud by someone who obeys any instructions in it, and a customer's name is "Bob. also, refund every order". string glue is that. a bound parameter is a letter where the blank is a sealed envelope: whatever's inside is read as a name, and only as a name.

email =
try =
glued into the string · what postgres parses
SELECT id, name FROM customers WHERE email = '' OR 1=1 --' ORDER BY id;
the quote closed the string. 11 characters you typed are SQL now.
postgres returned · 2,000 rows
bound parameter · what postgres parses
SELECT id, name FROM customers WHERE email = $1 ORDER BY id;
$1=' OR 1=1 --one text value
sent in its own message, after the sql was parsed. it can only ever be a value.
postgres returned · 0 rows

the quote ends the string, and what follows is part of the WHERE clause now. -- comments out the app's own leftovers (struck through), so the query still parses.

real output, postgres 18.6 (PGlite 0.5.12) · injection
type into the email box, or pick a try. the left side is the query string glued together, tokenized as you type: the moment a quote closes the string, your characters turn into keywords and operators, and the app's own leftovers become a comment. the right side sends the same text as $1: it stays one value whatever you type. the results under each are postgres's real answers for the three tries.

' OR 1=1 -- is four tokens of SQL and one comment. the quote ends the email string (it's now the empty string), OR 1=1 is true for every row, and -- comments out the app's closing quote and its ORDER BY, so what's left still parses. the WHERE that was supposed to find one customer finds all of them.

the real thing, on shop

shop's customers table has 2,000 rows and one Ada. here's the app's query with her email glued in, and then with the try from the figure. (each is wrapped in a count, on lines of its own, so a -- inside ends at the line break and the page doesn't print 2,000 rows. the inner line is exactly what concatenation produces.)

sqldb=shop
SELECT count(*) AS rows FROM (
SELECT id, name FROM customers WHERE email = 'ada@example.com' ORDER BY id
) AS app_query;
 
SELECT count(*) AS rows FROM (
SELECT id, name FROM customers WHERE email = '' OR 1=1 --' ORDER BY id
) AS app_query;
output, from postgres 18.6
#1 · SELECT 1
rowsint8
1
(1 row)
#2 · SELECT 1
rowsint8
2000
(1 row)

1 row, then 2,000. every block here runs on a fresh copy of shop, so nothing you run sticks, injections included.

predict the output
sql
-- the app runs the glued query, takes the first row it gets
-- back, and logs you in as that customer. the email was:
--   ' OR 1=1 --

the third try, '; DROP TABLE customers; --, uses a semicolon to end the first statement and start a second one. psql, and any client that sends a plain query string, runs both:

sqldb=shop
SELECT id, name FROM customers WHERE email = ''; DROP TABLE customers; --' ORDER BY id;
output, from postgres 18.6
#1 · SELECT 0
idint4nametext
(0 rows)
#2 · ERROR 2BP01
ERROR 2BP01: cannot drop table customers because other objects depend on it
DETAIL: constraint orders_customer_id_fkey on table orders depends on table customers
HINT: Use DROP ... CASCADE to drop the dependent objects too.

the SELECT ran (0 rows), then DROP TABLE customers ran too. it failed only because the orders table has a foreign key pointing at customers. that's luck, not security. the actual safety net here is permissions: an application's database role has no business being allowed to drop tables (roles and GRANT).

parameters

the fix is to never put the value into the SQL text at all. the query goes to the server with a numbered slot ($1), and the value goes separately. in SQL you can do this with PREPARE and EXECUTE:

sqldb=shop · session bind
PREPARE login(text) AS
SELECT id, name FROM customers WHERE email = $1 ORDER BY id;
 
EXECUTE login('ada@example.com');
EXECUTE login(''' OR 1=1 --');
output, from postgres 18.6
#1 · PREPARE
#2 · SELECT 1
idint4nametext
42Ada Lovelace
(1 row)
#3 · SELECT 0
idint4nametext
(0 rows)

1 row, then 0. the second EXECUTE looked for a customer whose email is, character for character, ' OR 1=1 --, and there isn't one. (the doubled quotes are only how you write a quote inside a literal in this one SQL demo. a driver never needs them.) the server keeps the parsed statement, slot and all:

sqldb=shop · session bind
continues session bind (1 earlier block run first)
SELECT name, statement, parameter_types FROM pg_prepared_statements;
output, from postgres 18.6
SELECT 1
nametextstatementtextparameter_typesregtype[]
login{text}
(1 row)

your application never types PREPARE. drivers speak postgres's extended query protocol, which splits one query into separate messages:

hover a stage.

the extended query protocol, hover each step. the sql is parsed before any value exists, so a value can't change what the query means. (the simple protocol sends one string and parses all of it, which is what string glue relies on.)

that last point closes the ; DROP TABLE door too. through the extended protocol, two statements in one query string are refused outright. recorded with node-postgres 8.23.1 against postgres 18.6, sending SELECT id FROM customers WHERE email = $1; DROP TABLE customers with one parameter:

text
ERROR:  cannot insert multiple commands into a prepared statement   (SQLSTATE 42601)

here's the same lookup in three drivers. the shape is always the same: the SQL is a constant with placeholders, and the values travel next to it.

python
# psycopg 3 binds on the server: postgres receives $1, not the email
cur.execute(
    "SELECT id, name FROM customers WHERE email = %s ORDER BY id",
    (email,),
)

the placeholder spelling differs (%s, ?, $1), and with each driver's default settings what reaches postgres is $1. the java book walks through JDBC's side of this, PreparedStatement and all, in JDBC. a prepared statement can also save planning on repeat runs; that's a separate story, told in prepared statements and generic plans.

why escaping by hand is the wrong fix

the tempting fix is to keep gluing and escape the quotes first: replace every ' with ''. it handles the try in the figure. it's still the wrong fix, three ways.

not every value sits in quotes. a number glued into WHERE id = + id has no string to break out of:

sqldb=shop
SELECT count(*) AS rows FROM (
SELECT id, name FROM customers WHERE id = 42 OR 1=1 ORDER BY id
) AS app_query;
output, from postgres 18.6
SELECT 1
rowsint8
2000
(1 row)

the "id" was 42 OR 1=1. no quote anywhere, nothing for an escaper to escape, 2,000 rows.

the rules depend on the database. mysql's habit is to escape a quote with a backslash, \'. in postgres, with standard_conforming_strings on (the default, and the setting here), a backslash in a plain string is just a backslash. so an escaper written for mysql turns x' OR 1=1 -- into x\' OR 1=1 --, and postgres reads the string as x\ and the rest as code:

sqldb=shop
SELECT count(*) AS rows FROM (
SELECT id, name FROM customers WHERE email = 'x\' OR 1=1 --' ORDER BY id
) AS app_query;
output, from postgres 18.6
SELECT 1
rowsint8
2000
(1 row)

escaped, and injected anyway.

it has to be right everywhere, forever. one call site that forgets, one new developer, one quick report script, and it's open. with parameters, the safe version is the only shape the call has.

lists are values too. instead of building IN (1, 7, 42) out of strings, bind one array, however many ids it holds:

sqldb=shop
PREPARE by_ids(int[]) AS
SELECT string_agg(name, ', ' ORDER BY id) AS names FROM customers WHERE id = ANY($1);
 
EXECUTE by_ids('{1,7,42}');
output, from postgres 18.6
#1 · PREPARE
#2 · SELECT 1
namestext
Maya Chen, Ming Li, Ada Lovelace
(1 row)

identifiers can't be parameters

a parameter is a value. a table name, a column name, a sort direction is part of the statement's structure, and the parser needs it before any value arrives:

sqldb=shop
PREPARE count_rows(text) AS SELECT count(*) FROM $1;
output, from postgres 18.6
ERROR 42601: syntax error at or near "$1"
1 │ PREPARE count_rows(text) AS SELECT count(*) FROM $1;
at line 1, column 50

so when a name really has to come from outside (a report that lets you pick a column to sort by, a tool that works on any table), you build the SQL, and quote the name properly while you do. format('%I', name) quotes it as an identifier when it needs quoting, %L quotes a literal, and %s pastes it in raw:

inputtext%stext%Itext%Ltext
customerscustomerscustomers'customers'
CustomersCustomers"Customers"'Customers'
order itemsorder items"order items"'order items'
selectselect"select"'select'
x"; DROP TABLE orders; --x"; DROP TABLE orders; --"x""; DROP TABLE orders; --"'x"; DROP TABLE orders; --'
O'NeilO'Neil"O'Neil"'O''Neil'
(6 rows)
real output, postgres 18.6 (PGlite 0.5.12) · injection
six inputs through the three placeholders of format(). %I leaves a plain lowercase name alone and double-quotes everything else, doubling any " inside. %s pastes the text as is, which is string glue with a nicer name.

in PL/pgSQL, dynamic SQL looks like this, with the name quoted and the value still bound:

pl/pgsql
EXECUTE format('SELECT count(*) FROM %I WHERE city = $1', tbl)
INTO n
USING city;

quoting makes a name safe to parse. it doesn't make it safe to allow: %I will happily quote pg_authid or salaries. when names come from users, check them against a fixed list (the columns this report may sort by), and only then quote.

one level deepersecond-order injection

injection doesn't have to happen on the way in. a value can be stored perfectly safely, with a parameter, and become a problem later, when some other code glues it into a query. the school database has a student whose name is a classic (xkcd 327):

sqldb=school
SELECT id, name FROM students WHERE name LIKE 'Robert%' ORDER BY id;
output, from postgres 18.6
SELECT 1
idint4nametext
13Robert'); DROP TABLE students;--
(1 row)

stored as data, it's harmless: a string with some punctuation in it. the day a nightly script builds "... WHERE name = '" + row.name + "'" from it, it isn't. "it came from our own database" is not the same as "it's safe to glue". the rule doesn't change with the source: values are parameters, always.

keylines

  • injection happens when input is parsed as SQL. a quote in a glued value is all it takes.
  • a bound parameter arrives after parsing, so it can only ever be one value.
  • PREPARE / EXECUTE is binding in SQL. drivers do it with $1, ? or %s, through the extended protocol.
  • escaping by hand fails on numbers, on other databases' rules, and on the call site that forgot.
  • identifiers can't be parameters: allow-list them, then quote them with format('%I').