Square CloudSquare Cloud

What is SQL injection and how to prevent it

SQL injection is an attack where text sent by a user becomes part of a SQL command and changes what the database runs. The main defense is a parameterized query, which sends the command and the values separately.

Updated 7 min read

Learning objectives

After reading this article you will be able to:

  • Understand how user input turns into a SQL command
  • Fix queries with parameters in Node.js (pg) and Python (psycopg)
  • Know where an ORM still leaves a gap and how least privilege limits the damage
On this page

Every application that stores data in a relational database builds SQL queries. When a query is built by gluing fixed text to whatever came from a form, a URL or a bot command, the person typing gets to write part of the SQL. That is SQL injection, one of the oldest flaws on the web.

The fix is well known, short and needs no paid tool: keep the command apart from the values. This article shows the attack, the fix in Node.js and Python, the places where an ORM does not protect you and how to shrink the damage if something slips through.

What is SQL injection?#

SQL injection is a flaw where data supplied by a user is read as part of the SQL command instead of as a value. The database cannot tell which parts of the string came from your code and which came from a stranger: it receives text and runs it.

That lets an attacker read tables they should not see, change or delete rows, log in without a password and, depending on the database user's permissions, run administrative commands. APIs, Discord bots, admin areas and search boxes are all exposed the same way: it takes one input that reaches the SQL through concatenation.

How does a SQL injection attack work?#

Picture a route that looks up a user by the email they typed:

js
// VULNERABLE: the typed email goes straight into the SQL string
const email = req.body.email;
const { rows } = await pool.query(
  `SELECT id, name FROM users WHERE email = '${email}'`,
);

With a normal email, it works. Now someone types this into the field:

text
' OR '1'='1

The string that reaches the database becomes:

sql
SELECT id, name FROM users WHERE email = '' OR '1'='1'

The attacker's quote closes the text, and OR '1'='1' is always true. The query returns every user, and a login that trusts the first row signs into someone else's account.

The same trick has variations. With UNION SELECT, the attacker appends columns from another table to the result, such as password hashes. When the page does not show the result, they ask true-or-false questions (or run queries that are slow on purpose) and infer the data bit by bit, which is called blind SQL injection.

Chaining a second statement, as in '; DROP TABLE users; --, depends on the driver. In PostgreSQL, pg and psycopg accept several statements separated by ; in a query sent without parameters, like the vulnerable one above; with parameters, the server refuses. In MySQL, the mysql and mysql2 drivers only accept several statements if the connection turns on multipleStatements. Even without that, the tampered SELECT alone already leaks data.

How do you prevent SQL injection with parameterized queries?#

A parameterized query (also called a prepared statement) defines the command with placeholders where the values go and hands the values over separately, through the driver's API. OWASP lists it as the preferred pattern: the value is never read as SQL, no matter how many quotes it contains.

Node.js with pg#

js
import pg from "pg";

const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });

export async function findUser(email) {
  const { rows } = await pool.query(
    "SELECT id, name FROM users WHERE email = $1",
    [email],
  );
  return rows[0] ?? null;
}

In node-postgres, the placeholders are $1, $2 and so on, and the values go in an array. The docs explain that the query text travels unaltered to PostgreSQL, which substitutes the values safely. With the payload from before, the database looks for a user whose email is literally ' OR '1'='1 and finds nobody. In MySQL with mysql2, the placeholder is ?; the idea is the same in every driver.

Python with psycopg#

python
import os

import psycopg


def find_user(email: str):
    with psycopg.connect(os.environ["DATABASE_URL"]) as conn:
        return conn.execute(
            "SELECT id, name FROM users WHERE email = %s",
            (email,),
        ).fetchone()

In psycopg, the placeholder is %s (or %(name)s with a dict), with no quotes around it, and the values go in a sequence: (email,), with the comma, is a one-item tuple. That %s is not Python string formatting; the driver does the substitution. The docs are blunt: never use % or + to merge values into a query.

To set up the connection, the pool and TLS, see how to connect PostgreSQL to Node.js and how to connect PostgreSQL to Python.

What if the value is a column name?#

Parameters replace values, not identifiers. The node-postgres docs say it plainly: PostgreSQL does not support parameters for table or column names. This comes up whenever users choose how a list is sorted. OWASP's answer is an allow-list: the user picks an option, and your code maps it to a fixed value you wrote.

js
const COLUMNS = new Map([
  ["name", "name"],
  ["newest", "created_at"],
]);

export async function listUsers(sort, direction) {
  const column = COLUMNS.get(sort) ?? "created_at";
  const order = direction === "asc" ? "ASC" : "DESC";
  const { rows } = await pool.query(
    `SELECT id, name FROM users ORDER BY ${column} ${order} LIMIT $1`,
    [50],
  );
  return rows;
}

The interpolation is safe here because column and order can only hold values from your code. When an identifier really has to be dynamic, use the driver's helpers: sql.Identifier in psycopg and escapeIdentifier in pg.

Does an ORM prevent SQL injection?#

Most of the time, yes. ORMs such as Prisma and Django's generate parameterized queries when you use their normal find and filter methods. The gap opens when you step out of the ORM to write SQL by hand and glue the text together with interpolation.

In Prisma, the tagged template is safe and the method with "Unsafe" in its name escapes nothing:

js
// prisma: your project's PrismaClient instance

// SAFE: tagged template, the value goes as a parameter
const users = await prisma.$queryRaw`SELECT id, name FROM "User" WHERE name = ${name}`;

// VULNERABLE: string built by hand in the Unsafe method
const unsafe = await prisma.$queryRawUnsafe(
  `SELECT id, name FROM "User" WHERE name = '${name}'`,
);

In Django, raw() takes the values in params:

python
# SAFE: unquoted placeholder and values in params
Person.objects.raw("SELECT * FROM app_person WHERE last_name = %s", [last_name])

# VULNERABLE: the f-string builds the SQL before Django sees it
Person.objects.raw(f"SELECT * FROM app_person WHERE last_name = '{last_name}'")

Rules of thumb: be suspicious of any method with raw, unsafe or literal in its name. In Prisma, Prisma.raw() with user text reopens the hole. In Django, never put quotes around %s: the docs warn that this exposes the query too. To pick an ORM, see Prisma, Drizzle, TypeORM or Sequelize.

How does least privilege limit the damage?#

A parameterized query closes the door. Least privilege decides how bad things get if a door stays open somewhere in the code. OWASP asks, in capital letters, not to give DBA or admin access to the accounts your application uses, and recommends one database user per application, with access only to what it needs.

In PostgreSQL, that looks like this:

sql
-- application user: reads and writes data, but cannot change the schema
CREATE ROLE app_shop LOGIN PASSWORD 'change-this-password';
GRANT CONNECT ON DATABASE shop TO app_shop;
GRANT USAGE ON SCHEMA public TO app_shop;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO app_shop;
GRANT USAGE ON ALL SEQUENCES IN SCHEMA public TO app_shop;

With this user, an injected DROP TABLE fails, because only the table owner, the schema owner or a superuser can drop it. Migrations run as another user that owns the schema, whose password never ships with the app. A reporting job that only reads gets a user with SELECT alone. ON ALL TABLES covers the tables that already exist; for future ones, use ALTER DEFAULT PRIVILEGES.

Three extras round it out: validate the input's format (an ID is a number), keep the connection string in an environment variable (how to keep secrets out of code) and never show users the database's error message, which teaches the attacker the shape of your tables.

Does a WAF solve SQL injection?#

A WAF with injection rules recognizes many known payloads, such as ' OR '1'='1 and UNION SELECT, and returns a 403 before the request reaches the application. But it only sees the request, not your code: an obfuscated payload or a field it does not inspect gets through. It is useful as a temporary patch while you fix a flaw, never as the fix. The same reasoning applies to XSS, the browser-side injection.

Layer What it does Replaces the parameterized query?
Parameterized query Keeps command and value apart It is the fix
Allow-list Maps column names and sort direction Complements it where there is no parameter
Input validation Rejects invalid formats No
Least privilege Limits what an attack can do No, it reduces the damage
WAF Blocks known patterns at the edge No

How to do this on Square Cloud#

PostgreSQL, MySQL, MongoDB and Redis hosting on Square Cloud starts on the Standard plan. You create the database from the dashboard and get the full connection URL, shown once at creation. Copy that URL into an environment variable of your application, like the DATABASE_URL in the examples above, instead of writing it in the code. The connection requires TLS, with the certificate the dashboard offers for download.

Every plan includes a WAF, but it is a generic layer at the edge, not a guarantee against injection: the fix is still the parameterized query in your code. If an attack does delete data, the automatic daily database snapshots let you restore an earlier snapshot into the same database, another one of the same engine or a new one.

See engines, limits and plans on the database hosting page.

Infrastructure

L3/L4/L7 DDoS mitigation and a WAF on every plan

Database hosting

FAQs

Does an ORM prevent SQL injection?

It does for the queries it builds, because it sends values as parameters. The gap comes back when you write raw SQL with string interpolation, as with Prisma's `$queryRawUnsafe` or a Django `raw()` built with an f-string.

Does escaping quotes prevent SQL injection?

Not reliably. OWASP strongly discourages escaping values by hand, because one missed case is enough. Use parameterized queries, which keep the command apart from the data.

Is input validation enough?

No. Validation helps (an ID should be a number, an email should look like an email), but OWASP treats it as a complement. Even a validated value should go in as a parameter.

Can I pass a column name as a parameter?

No. Parameters replace values, not table or column names. To sort by a column the user picked, map the choice through a fixed allow-list of columns.

Does a WAF stop SQL injection?

A WAF with injection rules blocks many known patterns, but an obfuscated payload can get through. It is a second layer; the fix lives in the query in your code.

Next articleWhat is a brute force attack and how to defend against itA brute force attack tests passwords in bulk until one works. Learn the types (spraying, credential stuffing), how they work and the defenses, with code that runs.

More in Security

See all 24 articles