{"canonical_url":"https://engineer.company/glossary/sql-injection/","content_markdown":"# SQL injection\n\n## What it is\n\nSQL injection, often shortened to SQLi, is the attack in which an application\nbuilds an SQL command out of text that someone else supplied, and the database\nends up reading part of that text as SQL rather than as a value. The Common\nWeakness Enumeration lists it as CWE-89 and describes the weakness as a command\nbuilt wholly or partly from outside input, without first neutralising the\ncharacters that carry special meaning in SQL. OWASP's prevention cheat sheet\nputs the same idea more plainly: the attack works when untrusted data becomes\npart of the syntax of a query.\n\nThe root of the trouble is that SQL draws no firm line between the instructions\nin a command and the data inside it. A single quotation mark ends a string\nliteral, and whatever the attacker types after it is parsed as more SQL. Two\nhyphens start a comment, which lets the attacker discard the rest of the\ndeveloper's statement. A semicolon, where the database and driver allow it, ends\none statement and starts another. None of them is exotic: the same marks turn up\nin surnames and free text.\n\nOWASP's Web Security Testing Guide sorts the attacks into three classes by how\nthe results reach the attacker. In-band attacks read the answer through the same\nchannel they used to send it, typically on the application's own page.\nOut-of-band attacks have the database deliver the results somewhere else, for\ninstance over a separate HTTP connection. Inferential or blind attacks receive\nno data at all, and rebuild it one question at a time from how the application\nbehaves. The guide names five common techniques across those classes: a `UNION`\noperator that joins a second `SELECT` onto the first, Boolean conditions, errors\nprovoked on purpose, out-of-band requests, and deliberate time delays.\n\nSQL injection belongs to a larger family. In CWE it sits under the general\ninjection weakness, CWE-74, alongside cross-site scripting, and the OWASP Top\nTen for 2025 places both in its A05 Injection category. The common thread is\ndata crossing a boundary into a place where it is read as instructions. Here the\ninterpreter is the database's SQL parser, and the cure is to keep every value\nout of the SQL text altogether.\n\n## Why it matters\n\nThe damage depends on what the application's database account may do, and that\nis often a great deal. CWE-89 lists reading data the attacker should never see,\ngetting past authentication without knowing a password, changing the data that\ndecides who may do what, modifying or deleting records, and in some set-ups\nrunning operating-system commands. OWASP's attack page adds administrative\noperations such as shutting the database down, reading files from the database\nserver, and taking over the database server as its administrator.\n\nBoth sources rate it severe. CWE gives the likelihood of exploit as High, and\nOWASP's attack page describes the flaw as both easy to find and easy to exploit.\nThe weakness appears in every edition of the CWE Top 25 Most Dangerous Software\nWeaknesses from 2019 to 2025. The CWE entry also records a 2008 wave in which\none SQL injection string, working against many different programs, compromised a\nlarge number of web servers and made them serve malicious code.\n\nThe defence, by contrast, is well understood and cheap. OWASP's cheat sheet\nmakes prepared statements with bound parameters its first defence, and CWE\nrecommends them too: the SQL and the values travel separately, so the database\ncannot mistake one for the other. Everything else, from least privilege to\ncareful error handling, is a second layer that limits the damage when a mistake\nslips through.\n\n## What it looks like in practice\n\nTake a shop whose order history page looks up orders by the email address typed\ninto a form. The developer builds the SQL with a Python f-string:\n\n```python\ncur.execute(f\"SELECT id, total FROM orders WHERE email = '{email}'\")\n```\n\nA visitor types `x' OR '1'='1` into the field. The program pastes it in, and the\ndatabase receives this:\n\n```sql\nSELECT id, total FROM orders WHERE email = 'x' OR '1'='1'\n```\n\nThe quotation mark after `x` closes the string the developer opened, and the\n`OR` clause after it is always true, so the database returns every order in the\ntable. CWE-89 and the testing guide use the same always-true trick, which can\nalso let a login form accept a visitor who knows neither the username nor the\npassword.\n\nA worse input ends the statement and starts another. The CWE entry's example\nenters `name'; DELETE FROM items; --` as an item name, so that a second\nstatement follows the first and the hyphens comment out the rest. Whether that\nruns depends on the database and the driver, and several current interfaces\nrefuse it. PostgreSQL's `PQexecParams` takes at most one SQL command per string,\nwhich its documentation counts as of some use against SQL injection. Python's\n`sqlite3` module raises an error whenever `execute()` receives more than one\nstatement, and psycopg refuses several statements in one call whenever\nparameters are passed. None of that stops the always-true condition above, which\nneeds only one statement.\n\nThe fix is to pass the value separately. PEP 249, Python's database interface\nstandard, has each driver declare its placeholder style in a module constant\ncalled `paramstyle`, and lists five styles: `qmark` (`?`), `numeric` (`:1`),\n`named` (`:name`), `format` (`%s`) and `pyformat` (`%(name)s`). The `sqlite3`\nmodule is fixed to `qmark` and also accepts `named`. Psycopg, the PostgreSQL\ndriver, takes `%s` and `%(name)s`:\n\n```python\ncur.execute(\n    \"SELECT id, total FROM orders WHERE email = %s\",\n    (email,),\n)\n```\n\nThe `%s` looks like Python string formatting, but nothing is formatted: the SQL\nand the tuple of values reach the driver as two separate arguments. Psycopg 3\nkeeps them apart all the way, sending the command and its parameters to the\nserver separately rather than merging them on the client. OWASP's cheat sheet\nmakes the point with its own sample input, `tom' or '1'='1`: bound as a\nparameter, it is a strange user name looked up literally, and it matches nobody.\n\nPostgreSQL offers the same split in plain SQL. `PREPARE` fixes the statement\nwith numbered parameters, and `EXECUTE` supplies the values later:\n\n```sql\nPREPARE order_lookup (text) AS\n    SELECT id, total FROM orders WHERE email = $1;\nEXECUTE order_lookup('x'' OR ''1''=''1');\n```\n\nThe hostile input, written here as an SQL literal, arrives in `$1` as one\nodd-looking email address and finds no orders.\n\nOn a platform holding professional and organisational data, input is validated\nbefore anything touches the database, and then\n[the API connects as a least-privilege role that may only execute the app's functions](/portfolio/hardened-the-application-with-nonce-based-csp/),\nwith everything parameterised. Binding keeps data from turning into SQL, and the\nnarrow role limits what a mistake could reach.\n\n## Where it goes wrong\n\n**Building the string anyway.** An f-string, the `%` operator, `+` or\n`.format()` merges the value into the SQL before the driver sees it, and so does\na placeholder written inside quotation marks, such as `'%s'`. OWASP notes that\nconcatenating untrusted values before preparing a statement defeats the whole\nprotection, and psycopg's documentation tells developers never to use `%` or `+`\nto merge values into queries. Pass every value as the second argument of\n`execute()`, with the placeholder bare.\n\n**Escaping by hand.** Doubling quotation marks or adding backslashes looks\nequivalent, but the rules depend on the SQL dialect and its settings. OWASP's\nexample is MySQL's `NO_BACKSLASH_ESCAPES` mode, which switches backslash\nescaping off, and the cheat sheet marks escaping as strongly discouraged.\nReplace hand-escaped strings with bound parameters.\n\n**Validation or a WAF treated as the fix.** Validation catches mistakes, but\nfree text has to allow the characters an attacker needs: the CWE entry's example\nis the surname O'Reilly, which would likely pass validation and still contains a\nquotation mark. Denylists of dangerous words have loopholes, and CWE rates an\napplication firewall's effectiveness as only moderate. As OWASP puts it,\n\"Validation of a value does not make it safe to concatenate into SQL.\" Keep\nvalidating for correctness, and bind for safety.\n\n**Table names, column names or sort order taken from input.** Placeholders stand\nfor values only, so a developer who needs a user to choose a column or the\ndirection of `ORDER BY` is tempted to paste the text in. OWASP's answer is to\nmap each choice to a small set of names the application owns and to reject\nanything else, for example turning a requested direction into the literal `ASC`\nor `DESC`. When a name really must be dynamic, psycopg's `psycopg.sql` module\ncomposes identifiers, though OWASP notes that quoting a name does not limit\nwhich tables the application can be steered to.\n\n**Stored procedures assumed to be safe.** Calling a procedure with bound\narguments protects the call, not the SQL the procedure builds inside itself. CWE\nnotes that using a stored procedure rules out only some injection paths and\nleaves others possible. Inside the database, use static SQL, or bind values in\ndynamic SQL too; in PostgreSQL that means `EXECUTE ... USING` for values and\n`format('%I', ...)` for identifiers.\n\n**An ORM with strings stitched in.** An object-relational mapper binds values\nwhen it is used as designed, and CWE credits persistence layers such as\nHibernate with significant protection when used properly. OWASP adds that\nHibernate queries can still be injected when developers concatenate input into\nthe query text. Use the mapper's parameters, not string building.\n\n**An application account with administrator rights.** If the account can do\neverything, so can the attacker. OWASP asks for read-only accounts where only\nreads are needed, a separate database user for each web application, views that\nexpose only the columns an account needs, and no administrator rights for\napplication accounts. When an application works only through stored procedures,\nit should be allowed to execute those and nothing else. Least privilege limits\nthe damage; it does not prevent the injection.\n\n**Detailed database errors shown to users.** An error message that reveals the\nstatement's structure helps an attacker tailor the next attempt, and the testing\nguide's error-based technique relies on exactly that. CWE recommends minimal\nerror messages. Show the user a generic failure and keep the detail on the\nserver for the team.\n\n**Trusting data already in the database.** A value that was stored safely can\nstill be dangerous when a later piece of code pastes it into SQL. OWASP says its\ncontrols apply wherever the data originates, be it an HTTP request, another\nservice or an earlier write to storage, and CWE warns that later processes may\nforget to escape what was saved. Bind values read from your own tables just as\nyou bind input from a form.\n\n## Further reading\n\n- [CWE-89 in the Common Weakness Enumeration](https://cwe.mitre.org/data/definitions/89.html)\n  — the weakness entry: consequences, examples, and the mitigations with\n  their limits.\n- [OWASP SQL Injection Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html)\n  — parameterised queries, stored procedures, dynamic identifiers and least\n  privilege.\n- [OWASP Web Security Testing Guide: Testing for SQL Injection](https://wstg.owasp.org/v4.2/4-Web_Application_Security_Testing/07-Input_Validation_Testing/05-Testing_for_SQL_Injection/)\n  — the attack classes and techniques, as a tester meets them.\n- [PEP 249: Python Database API Specification v2.0](https://peps.python.org/pep-0249/)\n  — the interface Python drivers share, including the five placeholder\n  styles.\n- [Psycopg 3: Passing parameters to SQL queries](https://www.psycopg.org/psycopg3/docs/basic/params.html)\n  — the rules for placeholders and the right way to build dynamic SQL.\n- [PostgreSQL: Command Execution Functions](https://www.postgresql.org/docs/current/libpq-exec.html)\n  — how libpq sends parameters apart from the command string.\n\n\u003chttps://engineer.company/glossary/sql-injection/\u003e\n","date_modified":"2026-10-30T02:51:31Z","description":"How SQL injection lets typed input rewrite the commands a database runs, what an attacker gains, and why bound parameters stop it.","formats":{"gemtext":"https://engineer.company/glossary/sql-injection/index.gmi","gopher":"https://engineer.company/glossary/sql-injection/gophermap","html":"https://engineer.company/glossary/sql-injection/","json":"https://engineer.company/glossary/sql-injection/index.json","markdown":"https://engineer.company/glossary/sql-injection/index.md","pdf":"https://engineer.company/glossary/sql-injection/index.pdf"},"kind":"page","language":"en","title":"What is SQL injection?","url":"https://engineer.company/glossary/sql-injection/","version":1}