Skip to content

SQL Injection

SQL injection happens when a program builds a SQL statement by pasting in text a user typed. If that text contains SQL of its own, the database runs it as part of the statement. The user is no longer supplying a value; they are rewriting the query. It is one of the most common and most damaging security flaws in applications that use databases, and it is entirely preventable.

The examples use the Invoices table from the example database, searched from a small Python program.

A search box lets staff look up invoices by supplier. The program pastes whatever is typed into the query:

supplier = request.form["supplier"]
sql = "SELECT InvoiceID, Supplier FROM Invoices WHERE Supplier = '" + supplier + "'"
rows = db.execute(sql)

Typed in good faith, Kestrel Catering produces the intended query. But suppose someone types this instead:

x' OR '1'='1

The pasted-together statement becomes:

SELECT InvoiceID, Supplier FROM Invoices WHERE Supplier = 'x' OR '1'='1'

The typed quote mark closed the text value early, and the rest became SQL. Since '1'='1' is always true, the query returns every invoice in the table, whoever they belong to. Other input can do far worse, such as reading tables the search was never meant to touch, or changing and deleting data.

Never paste input into SQL. Write the statement with a placeholder, and pass the value separately:

supplier = request.form["supplier"]
rows = db.execute(
"SELECT InvoiceID, Supplier FROM Invoices WHERE Supplier = ?",
(supplier,),
)

The database receives the statement and the value apart, and treats the value purely as data. Given the same malicious input, it looks for a supplier literally called x' OR '1'='1, finds none, and returns nothing. Given Kestrel Catering, it returns Kestrel’s two invoices as before.

Every language and database library supports parameters, though the placeholder varies: ? in many libraries, %s in some Python drivers, $1 in PostgreSQL, and @name in .NET.

Parameters are the fix. These limit the damage if something is missed:

  • Least privilege. Connect with a database account that can do only what the application needs. A search page has no business being able to drop tables.
  • Allow-lists for names. Parameters carry values, not table or column names. If a user picks a sort column, check the choice against a fixed list in code rather than pasting it in.
  • No raw errors. Show users a plain message when a query fails, and keep the database’s own error text for the logs; it can reveal the structure of the tables.