One-Page Brief: SQL Injection for New Team Leads

This brief is for someone who has just become responsible for a small project, a student team or a first app, and needs to understand SQL injection well enough to ask the right questions. No coding background beyond the basics is assumed.

The issue

Most apps store data in a database and talk to it using a language called SQL. SQL injection happens when an app builds a SQL command by gluing user input straight into the command text. A user can then type something that changes the meaning of the command, for example to read other people's data or delete records.

A tiny illustration of the unsafe pattern:

# Unsafe: the user's text becomes part of the SQL command
query = "SELECT * FROM users WHERE name = '" + typed_name + "'"

If someone types ' OR '1'='1, the command now matches every user.

The safe pattern sends the command and the user's input separately, using a placeholder:

cursor.execute("SELECT * FROM users WHERE name = ?", (typed_name,))

The database treats the input purely as data, never as part of the command.

Why it matters

Three takeaways

  1. Ask: do we use placeholders everywhere? Every query that includes anything from a user, a form, a URL or a file should use parameters. String gluing in SQL is a red flag in code review.
  2. Frameworks help, but do not guarantee. ORMs and query builders use placeholders by default. Problems creep back in when developers write raw SQL by hand or build parts of queries, such as sort columns, from user input.
  3. Limit what the app's account can do. The database user the app logs in with should only have the permissions it needs. Then even a mistake causes less harm.

Questions to ask your team

QuestionA good answer sounds like
How do we build queries with user input?"Always with placeholders or the ORM."
Where do we write raw SQL?"In a few known places, all reviewed."
What can the app's database user do?"Read and write its own tables, nothing more."
How would we notice an attack?"Errors and unusual queries are logged and someone looks at them."

Further reading on this site

Outside this site, the OWASP project publishes free cheat sheets on preventing injection.

A free learning page for beginners. Practise on a test database, never on real customer data, and check the official documentation for your database version.