Best practices and SQL injection
Knowing how to write queries is half the job; the other half is writing them so they are safe, readable and easy to maintain. This lesson gathers the best practices that separate someone who knows SQL from someone who knows SQL in production. We start with the most famous vulnerability of database applications, SQL injection, because it is responsible for huge data leaks and is completely avoidable.
What SQL injection is
It happens when an application builds a query by pasting text that comes from the user. Imagine a customer search by email that assembles the query by concatenating what the user types. If someone types a text with quotes and SQL code, that text stops being data and becomes part of the statement: the attacker can read tables they should not, bypass a login or delete data. See how the final query changes when the value is malicious.
-- The application builds the text by concatenation:
-- "SELECT * FROM customers WHERE email = '" + user_input + "'"
-- Normal input: ana@example.com -> works as intended
SELECT * FROM customers WHERE email = 'ana@example.com';
-- Malicious input: ' OR '1'='1 -> the condition is always true: ALL customers leak
SELECT * FROM customers WHERE email = '' OR '1'='1';
-- Worse input: '; DROP TABLE customers; -- -> a second statement is injected
SELECT * FROM customers WHERE email = ''; DROP TABLE customers; --';The defense: parameterized queries
The solution is not to try to filter or escape quotes by hand, which always leaves some gap. The solution is to separate code from data: the query is sent to the server with placeholders ($1, $2 in PostgreSQL; ? in MySQL and SQLite) and the values separately. The engine always treats the value as data, never as part of the statement, however many quotes it contains. All serious libraries (psycopg, node-postgres, JDBC, SQLAlchemy and ORMs) support it; always use it when a value comes from outside, even from an internal form. SQL itself shows it with PREPARE and EXECUTE.
-- The query is fixed; the value travels separately as $1
PREPARE find_customer(TEXT) AS
SELECT customer_id, name FROM customers WHERE email = $1;
EXECUTE find_customer('ana@example.com'); -- 1 row
-- The malicious text is now just a strange email that matches nothing
EXECUTE find_customer('x'' OR ''1''=''1'); -- 0 rows
DEALLOCATE find_customer;Parameters protect values, but not table or column names. If you need to sort by a column chosen by the user, do not paste it into the query: compare it with a closed list of allowed columns in your application. Complement it with the principle of least privilege: the account used by the application should be able to do only what is necessary (for example SELECT, INSERT and UPDATE on certain tables), never be the superuser. That way, even if something fails, the damage is limited.
-- Least privilege: a role for the web application
CREATE ROLE shop_app LOGIN PASSWORD 'change-me-please';
GRANT SELECT ON customers, products, orders, order_items TO shop_app;
GRANT INSERT ON orders, order_items TO shop_app;
GRANT UPDATE (stock) ON products TO shop_app; -- only the stock column
-- No DELETE, no DROP, no access to anything else.Best practices checklist
- Never concatenate user text into a query: use parameters.
- Write the column list instead of SELECT * in application code; there are no surprises if the table changes.
- Every UPDATE and DELETE has a WHERE; test it first with a SELECT and inside a transaction.
- Define constraints (NOT NULL, UNIQUE, CHECK, FOREIGN KEY) in the database, not only in the application.
- Choose correct types: NUMERIC for money, DATE and TIMESTAMPTZ for dates, never dates as text.
- Index frequent JOIN and filter columns, and verify with EXPLAIN.
- Never store passwords in plain text: use a slow salted hash (bcrypt, argon2) computed in the application.
- Make backups (pg_dump) and test restoring them: a backup never tested for restore is not a backup.
- Structure changes through versioned migration scripts, not by hand in production.
- Format and comment your queries: one keyword per line, clear aliases, consistent names.
✎ My notes
Saved only in this browser. Sign in to keep it in your account.0/5000 characters