CSE Roadmap

Common tier · about 3 hours · 5 parts

Part 4 of 5 · 2 min read

SQL injection

How untrusted input can rewrite a query's meaning, and why parameterized queries prevent it.

SQL injection

Think of a form letter with a blank left for someone's name. A mischievous person fills in not just a name, but an entire extra sentence. Read aloud, it changes the meaning of the whole letter.

In plain words: SQL injection happens when user input is inserted directly into a SQL statement's text, letting a malicious input change the statement's actual structure, not just its intended value. A parameterized query keeps user input strictly as a data value, never as part of the SQL text itself, which prevents this entirely.

A worked example. Building a query by directly concatenating user input lets an input like 107 OR 1=1 turn a single-customer lookup into a lookup matching every row.

The key lines.

-- vulnerable: building SQL text directly from user input
"SELECT * FROM orders WHERE customer_id = " + user_input

-- safe: the value is passed separately, never inserted into the SQL text
SELECT * FROM orders WHERE customer_id = $1;  -- $1 bound separately to user_input

SQL injection, parameterized query

SQL injection is an attack where untrusted input is inserted directly into SQL text, changing the statement's actual structure. A parameterized query passes input values separately from the SQL text, so they can never alter that structure.

Example: customer_id = $1 with $1 bound to "107 OR 1=1" still searches only for a literal matching value, never reinterpreting it as SQL logic.

Remember this

Never build a SQL statement by directly joining strings with raw user input. Parameterized queries, supported by essentially every real database driver, are the standard, complete fix, not merely a best practice to aim for when convenient.

Quick notes

  • GRANT gives permissions to a role or user; REVOKE removes them.
  • A role is a named set of permissions assignable to many users, changed in one place.
  • Least privilege means granting only what a role actually needs, never more.
  • SQL injection inserts untrusted input directly into SQL text, changing its structure.
  • Parameterized queries keep input as data only, completely preventing SQL injection.