SQL course · Module 11: Production SQL · Lesson 36 of 40
Quick answer: SQL injection happens when an app pastes user input into the text of a SQL query, so the input can change what the query does. SQL injection prevention starts with parameterized queries: the SQL has placeholders such as %s or $1, and the values are sent separately, so they are always treated as data. Then limit the damage with least privilege: the app connects as its own role that has only the rights it needs, given with GRANT. Escaping quotes by hand is not a safe replacement.
In this lesson you will learn:
- what SQL injection is, shown with one classic example on your own practice database
- how a parameterized query in Python (psycopg) blocks it, and why hand escaping is fragile
- how
PREPAREandEXECUTEuse parameters inside SQL itself - how to create a read-only app role with
CREATE ROLE,GRANTandREVOKE, and test it - how to remove the roles again with
DROP OWNEDandDROP ROLE
Before you start: the previous lesson was Lesson 35, PostgreSQL JSONB and Arrays for Semi-Structured Data; for this one you need Lesson 5, SQL WHERE Clause: Filter Rows with AND, OR, IN, BETWEEN and LIKE and Lesson 16, SQL CREATE TABLE: Data Types and Constraints. The Python part uses only basics from our Python course.
We ran every example on PostgreSQL 16.15 with the shop database from Lesson 3, Python 3.14.6 and psycopg 3.3.8 (its install page lists Python 3.10 to 3.15; 3.15 is the newest Python), and checked the current PostgreSQL 18 manual and the OWASP cheat sheet. Run this lesson only on your own practice database, as the postgres superuser. Never test injection on a system you do not own.
Table of Contents
What is SQL injection?
The OWASP cheat sheet puts it in one line: “SQL injection occurs when untrusted data becomes part of a query’s SQL syntax” (OWASP SQL Injection Prevention Cheat Sheet). If an app glues input such as a user name into the SQL text, a quote in the input can end the value early, and the rest becomes SQL.
A practice login table
For the demo we add a small login table. Passwords are never stored as text: crypt() with gen_salt('bf') from the pgcrypto extension stores a Blowfish-based (bcrypt) hash, and checking means hashing the typed password with the stored hash as salt (PostgreSQL docs: pgcrypto).
CREATE EXTENSION IF NOT EXISTS pgcrypto;
CREATE TABLE app_users (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
username text NOT NULL UNIQUE,
password_hash text NOT NULL
);
INSERT INTO app_users (username, password_hash) VALUES
('ayesha', crypt('lesson36-ayesha', gen_salt('bf'))),
('lucas', crypt('lesson36-lucas', gen_salt('bf'))),
('admin', crypt('lesson36-admin', gen_salt('bf')));
CREATE EXTENSION
CREATE TABLE
INSERT 0 3
The unsafe login: SQL built with an f-string
Install the driver with pip install "psycopg[binary]" (psycopg docs: Installation) in a virtual environment. Our script login_demo.py (run it with python login_demo.py) has two login functions. This is the wrong one:
def login_unsafe(cur, username, password):
# WRONG: the input is pasted into the SQL text
query = (
"SELECT id, username FROM app_users "
f"WHERE username = '{username}' "
f"AND password_hash = crypt('{password}', password_hash)"
)
print(" SQL sent:", query)
cur.execute(query)
return cur.fetchall()
With normal input it works. Now we type the classic example ' OR 1=1 -- as the user name:
[injection] username="' OR 1=1 --"
SQL sent: SELECT id, username FROM app_users WHERE username = '' OR 1=1 --' AND password_hash = crypt('anything', password_hash)
unsafe -> [(1, 'ayesha'), (2, 'lucas'), (3, 'admin')]
Look at the SQL that was sent. The quote in the input closed the user name, OR 1=1 is true for every row, and -- starts a comment, so the password check was ignored. The query returned all three users, including admin, without any password. An app that logs in the first row it gets would be fooled.
SQL injection prevention: parameterized queries
In the safe version, the SQL has %s placeholders, and the values go in a separate tuple:
def login_safe(cur, username, password):
# RIGHT: placeholders in the SQL, values passed separately
cur.execute(
"SELECT id, username FROM app_users "
"WHERE username = %s AND password_hash = crypt(%s, password_hash)",
(username, password),
)
return cur.fetchall()
The psycopg docs explain that “query and the parameters are sent to the server separately” (psycopg docs: Passing parameters to SQL queries). The server never reads the value as SQL. The full run of both functions:
[correct password] username='ayesha'
SQL sent: SELECT id, username FROM app_users WHERE username = 'ayesha' AND password_hash = crypt('lesson36-ayesha', password_hash)
unsafe -> [(1, 'ayesha')]
safe -> [(1, 'ayesha')]
[wrong password] username='ayesha'
SQL sent: SELECT id, username FROM app_users WHERE username = 'ayesha' AND password_hash = crypt('wrong', password_hash)
unsafe -> []
safe -> []
[injection] username="' OR 1=1 --"
SQL sent: SELECT id, username FROM app_users WHERE username = '' OR 1=1 --' AND password_hash = crypt('anything', password_hash)
unsafe -> [(1, 'ayesha'), (2, 'lucas'), (3, 'admin')]
safe -> []
The safe function looked for a user literally named ' OR 1=1 --, found none, and returned an empty list. OWASP says prepared statements “treat bound values as data rather than SQL syntax”.

Why escaping by hand is fragile
The unsafe code also breaks for honest users. A name with an apostrophe is enough:
[name with a quote] username="O'Brien"
SQL sent: SELECT id, username FROM app_users WHERE username = 'O'Brien' AND password_hash = crypt('x', password_hash)
unsafe -> ERROR SyntaxError: syntax error at or near "Brien"
safe -> []
You could try to fix this by doubling every quote yourself. OWASP marks “Escaping All Dynamic Inputs” as “STRONGLY DISCOURAGED”: it should not be used “as a substitute for parameter binding”, because “escaping depends on the SQL dialect and configuration”. One missed field, or one setting that changes how quotes or backslashes work, and the hole is back. Parameters have none of these problems.
Table and column names: use an allow-list
Placeholders work only for values. OWASP: “Parameter markers represent data values, not table names, column names, or SQL keywords such as ASC and DESC.” For a sort column chosen by the user, map the choice to a fixed list and reject anything else. psycopg’s sql.Identifier then quotes the name correctly:
def list_products(cur, sort_by):
# Column names cannot be parameters: map the choice to a fixed allow-list
allowed = {"name": "name", "price": "price"}
if sort_by not in allowed:
raise ValueError(f"cannot sort by {sort_by!r}")
query = sql.SQL("SELECT name, price FROM products ORDER BY {} LIMIT 3").format(
sql.Identifier(allowed[sort_by])
)
cur.execute(query)
return cur.fetchall()
[sort allow-list]
price -> [('Gel Pens 10-Pack', Decimal('6.75')), ('Notebook Pack', Decimal('12.50')), ('Wireless Mouse', Decimal('24.99'))]
colour -> ValueError: cannot sort by 'colour'
PREPARE and EXECUTE: parameters in plain SQL
PostgreSQL has parameters in SQL too. PREPARE creates a statement with $1, $2 and so on, and EXECUTE runs it with values (PostgreSQL docs: PREPARE):
PREPARE login (text, text) AS
SELECT id, username FROM app_users
WHERE username = $1 AND password_hash = crypt($2, password_hash);
EXECUTE login('ayesha', 'lesson36-ayesha');
EXECUTE login('ayesha', 'wrong password');
EXECUTE login(''' OR 1=1 --', 'anything');
PREPARE
id | username
----+----------
1 | ayesha
(1 row)
id | username
----+----------
(0 rows)
id | username
----+----------
(0 rows)
Inside a SQL string, '' means one quote, so the third call passes the same classic input as a value, and again no row matches. Prepared statements “only last for the duration of the current database session”; you can list them in pg_prepared_statements and remove one with DEALLOCATE login;. In Python, psycopg sends values separately for you, so in app code you just pass parameters.
Least privilege: CREATE ROLE and GRANT
Parameters stop injection. Least privilege limits the damage if a bug slips through anyway; OWASP is clear that “it does not prevent SQL injection”. The aim is to “minimize the privileges assigned to every database account”, and never to connect an app as an admin. In PostgreSQL, users and groups are both roles (PostgreSQL docs: CREATE ROLE). We make a group role that can only read, and a login role for the app that is a member of it:
CREATE ROLE lesson36_readonly NOLOGIN;
GRANT USAGE ON SCHEMA public TO lesson36_readonly;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO lesson36_readonly;
CREATE ROLE lesson36_app LOGIN PASSWORD 'lesson36-demo-only';
GRANT lesson36_readonly TO lesson36_app;
\dp customers shows the result. The letters come from the manual’s table: r is SELECT, a INSERT, w UPDATE, d DELETE (PostgreSQL docs: Privileges):
Access privileges
Schema | Name | Type | Access privileges | Column privileges | Policies
--------+-----------+-------+------------------------------+-------------------+----------
public | customers | table | postgres=arwdDxt/postgres +| |
| | | lesson36_readonly=r/postgres | |
(1 row)
PostgreSQL 17 added a MAINTAIN privilege (m), so newer versions show arwdDxtm for the owner.
Test the role: permission denied
After SET ROLE, “permissions checking for SQL commands is carried out as though the named role were the one that had logged in originally”; a superuser may pick any role (PostgreSQL docs: SET ROLE). Reading works; changing data does not:
SET ROLE lesson36_app;
SELECT current_user;
SELECT count(*) FROM customers;
SET
current_user
--------------
lesson36_app
(1 row)
count
-------
10
(1 row)
ERROR: permission denied for table customers
That error came from DELETE FROM customers WHERE id = 10;. UPDATE products SET price = 0 WHERE id = 1; gave permission denied for table products, and CREATE TABLE notes (txt text); gave permission denied for schema public, because since PostgreSQL 15 other roles may no longer create objects in the public schema of a new database (PostgreSQL 15 release notes). Run RESET ROLE; to become postgres again.
New tables and ALTER DEFAULT PRIVILEGES
GRANT ... ON ALL TABLES IN SCHEMA covers the tables that exist when you run it. We created a coupons table afterwards, and the app role got ERROR: permission denied for table coupons. Grant it on that table, and use ALTER DEFAULT PRIVILEGES, which sets privileges “that will be applied to objects created in the future” (PostgreSQL docs: ALTER DEFAULT PRIVILEGES):
GRANT SELECT ON coupons TO lesson36_readonly;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO lesson36_readonly;
After this, a new gift_cards table was readable by the app role with no extra GRANT.
REVOKE: take a right away
Not every reader should see password hashes. REVOKE removes a privilege from the group, and we grant it only to the login role that checks passwords (PostgreSQL docs: GRANT):
REVOKE SELECT ON app_users FROM lesson36_readonly;
GRANT SELECT ON app_users TO lesson36_app;
We then ran login_demo.py again, connected as lesson36_app, and got the same results: read access is all the login needs.
Try it yourself
Exercise 1: A catalog role
Create a role lesson36_catalog that can read only products. Test it with SET ROLE: read one product, then try to count the orders.
Exercise 2: Check privileges without SET ROLE
has_table_privilege(role, table, privilege) returns true or false. Use it to check whether lesson36_app may SELECT and DELETE on customers, and SELECT on app_users.
Exercise 3: A prepared search
Prepare a statement by_category that lists the names and prices of products in one category, cheapest first. Run it for Stationery and Home Office, then remove it.
Solutions
Solution 1
CREATE ROLE lesson36_catalog NOLOGIN;
GRANT SELECT ON products TO lesson36_catalog;
SET ROLE lesson36_catalog;
SELECT name, price FROM products WHERE id = 1;
SELECT count(*) FROM orders;
RESET ROLE;
CREATE ROLE
GRANT
SET
name | price
----------------+-------
Wireless Mouse | 24.99
(1 row)
ERROR: permission denied for table orders
RESET
The role can read only the table it was granted.
Solution 2
SELECT has_table_privilege('lesson36_app', 'customers', 'SELECT') AS can_select,
has_table_privilege('lesson36_app', 'customers', 'DELETE') AS can_delete,
has_table_privilege('lesson36_app', 'app_users', 'SELECT') AS can_read_users;
can_select | can_delete | can_read_users
------------+------------+----------------
t | f | t
(1 row)
The app role inherits SELECT on customers from its group and has its own SELECT on app_users.
Solution 3
PREPARE by_category (text) AS
SELECT name, price FROM products WHERE category = $1 ORDER BY price;
EXECUTE by_category('Stationery');
EXECUTE by_category('Home Office');
DEALLOCATE by_category;
PREPARE
name | price
------------------+-------
Gel Pens 10-Pack | 6.75
Notebook Pack | 12.50
(2 rows)
name | price
-----------------+--------
Desk Lamp | 32.00
Ergonomic Chair | 259.00
(2 rows)
DEALLOCATE
One statement, a different value each time. When you finish, run lesson36_cleanup.sql to remove the roles and tables.
Common mistakes
- Building SQL with f-strings,
+or%. Even with quotes around them, values pasted into the text are not safe. The psycopg docs showVALUES ('%s')with%as an example that “WILL FAIL MISERABLY”. Pass values as the second argument ofexecute. - Connecting the app as
postgres. A superuser can do anything, so one injection bug can destroy everything. Use a role with only the grants it needs. - Running PREPARE twice. The second time gives
ERROR: prepared statement "p" already exists. RunDEALLOCATE p;first. - Dropping a role that still has privileges.
DROP ROLE lesson36_readonly;givesERROR: role "lesson36_readonly" cannot be dropped because some objects depend on it, with a list such asprivileges for table customers. RunDROP OWNED BYthat role in each database first (PostgreSQL docs: Dropping Roles). Careful: it also drops any tables the role owns, so move those first withREASSIGN OWNED BY. - Expecting ALL TABLES to cover new tables. It does not; add
ALTER DEFAULT PRIVILEGES.
Frequently asked questions
Do parameterized queries prevent all SQL injection?
They protect every value passed as a parameter, but not table names, column names or keywords built as text; use an allow-list for those. OWASP also warns that stored procedures are “not automatically safe”: dynamic SQL built inside them needs the same care.
Is escaping quotes enough to stop SQL injection?
No. OWASP strongly discourages it, because escaping depends on the database and its settings, and it is easy to forget one field. Parameterized queries are simpler and safer, and they also handle names like O’Brien.
What privileges should an application database user have?
Only what the app needs: usually SELECT, and INSERT, UPDATE or DELETE on specific tables, never superuser or owner rights. OWASP adds that different apps should use different database users, and that read-only accounts should get read access only to the tables they need. For part of a table, it suggests granting SELECT on a view (Lesson 23) instead.
Summary
- SQL injection happens when input becomes part of the SQL text;
' OR 1=1 --turned our login check into “return every user”. - Parameterized queries send values separately from the SQL, so the input stays data; in psycopg use
%sand a tuple, in SQL usePREPAREand$1. - Escaping by hand is fragile; identifiers need an allow-list.
- Least privilege limits the damage:
CREATE ROLE,GRANTthe minimum,REVOKEthe rest, and test withSET ROLE. ALTER DEFAULT PRIVILEGEScovers future tables;DROP OWNEDmust run beforeDROP ROLE.
Next lesson
Next: Lesson 37, PostgreSQL Table Partitioning for Large Tables.
Sources
- OWASP Cheat Sheet Series: SQL Injection Prevention Cheat Sheet
- psycopg 3 documentation: Passing parameters to SQL queries
- psycopg 3 documentation: Installation
- PostgreSQL documentation: PREPARE
- PostgreSQL documentation: CREATE ROLE
- PostgreSQL documentation: GRANT
- PostgreSQL documentation: Privileges
- PostgreSQL documentation: SET ROLE
- PostgreSQL documentation: ALTER DEFAULT PRIVILEGES
- PostgreSQL documentation: DROP OWNED
- PostgreSQL documentation: Dropping Roles
- PostgreSQL documentation: pgcrypto
- PostgreSQL 15 release notes (public schema)
- PostgreSQL 17 release notes (MAINTAIN privilege)





