Password Password

Security, explained for the people who have to fix it.

Attack and Defense

SQL injection for people who write queries: mechanism, fix, test

How a string-built query lets input change the SQL, why parameterised queries end it, how often CISA's exploited record lists it, and a test to run.

SQL injection is old, well understood, and still on the OWASP Top 10, which is a strange combination until you notice why: the fix is easy, but it has to be applied to every query, and one that is built by pasting a value into a string undoes it. This article explains the mechanism for the person writing the query, shows the one-line change that closes it, quotes what OWASP and CWE-89 say, counts how often SQL injection appears in CISA's catalogue of exploited vulnerabilities, and ships a regression test that proves the safe version cannot be widened by hostile input. It describes the defect only as far as a developer needs to recognise and fix it in their own code; it is not a guide to attacking anyone's database.

The mechanism

A database receives a single string of SQL and executes it. When your code builds that string by concatenating user input, the input becomes part of the program. CWE-89 states the problem exactly: the product "constructs all or part of an SQL command using externally-influenced input", but "does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command", so "the generated SQL query can cause those inputs to be interpreted as SQL instead of ordinary user data".

The canonical illustration, from CWE-89, is a lookup that concatenates a name:

SELECT * FROM items WHERE owner = 'wiley' AND itemname = '<input>'

If the input is name' OR 'a'='a, the string the database receives becomes ... itemname = 'name' OR 'a'='a', and, as CWE-89 puts it, the "WHERE clause to always evaluate to true", so the query returns rows the caller was never supposed to see. The database did nothing wrong; it executed the program it was handed. The defect is that the program was partly written by the person supplying the input.

OWASP's Top 10:2021 places injection at position A03 and, from an analysis across contributed data, records 33 mapped CWEs, 274,228 occurrences, and 32,078 CVEs for this category, with a maximum incidence rate of 19.09%. Those numbers are why the fix being easy is not the same as the problem being solved: it has to be applied everywhere, and legacy code accumulates the exceptions.

SQL injection in the exploited record

A Top 10 rank says how often testers find a weakness class in applications. The question a defender has to answer is narrower: is SQL injection still being used against real systems now, and in what kind of software? Two public US-government records answer it with counts. The National Vulnerability Database (NVD) holds every published CVE with the weakness types assigned to it, and the Known Exploited Vulnerabilities (KEV) catalogue from CISA lists the CVEs that CISA has evidence of attackers using. We downloaded both on 30 October 2026 (KEV catalogue version 2026.10.29, 1,764 entries; NVD through its CVE API 2.0) and counted every CVE whose NVD record lists CWE-89, from either NVD's analysts or the CVE's own numbering authority, which is what the NVD API's cweId filter matches. The analysis script is sql-injection-in-the-exploited-record.py; the per-year counts and the list of KEV SQL-injection entries are in the Code and data box and in sql-injection-kev-entries.csv. This product uses the NVD API but is not endorsed or certified by the NVD.

python code/sql-injection-in-the-exploited-record.py --fetch kev_nvd_raw --csv-dir out

Across the whole NVD, 11,827 of 397,994 non-rejected CVEs list CWE-89 (2.97%). The share peaked in 2008, when 19.39% of the year's CVEs were SQL injection, and has stayed between 1.46% and 5.96% in every year from 2012 to 2025:

Year CVEs published CWE-89 Share KEV entries added that year of which CWE-89
2006 6,608 98 1.48% n/a n/a
2007 6,516 255 3.91% n/a n/a
2008 5,632 1,092 19.39% n/a n/a
2009 5,732 948 16.54% n/a n/a
2010 4,639 515 11.10% n/a n/a
2011 4,150 289 6.96% n/a n/a
2012 5,288 234 4.43% n/a n/a
2013 5,187 146 2.81% n/a n/a
2014 7,928 291 3.67% n/a n/a
2015 6,494 213 3.28% n/a n/a
2016 6,449 94 1.46% n/a n/a
2017 14,642 504 3.44% n/a n/a
2018 16,510 501 3.03% n/a n/a
2019 17,305 546 3.16% n/a n/a
2020 18,322 443 2.42% n/a n/a
2021 20,149 606 3.01% 311 5
2022 25,073 1,494 5.96% 555 6
2023 28,816 955 3.31% 187 3
2024 39,953 650 1.63% 186 5
2025 48,151 1,305 2.71% 245 4
2026 89,116 567 0.64% 280 9

What the two records show:

  • SQL injection is exploited about as often as it is disclosed. CWE-89 is 2.15% of the CVEs published since the start of 2022 (4,971 of 231,109), and 2.22% of the KEV entries for CVEs published in the same period (19 of 857). In CISA's record, its share of exploited CVEs matches its share of new ones.
  • It is a steady minority, not a leading cause. 32 of the 1,764 entries in the catalogue are SQL injection (1.81%), tied with cross-site scripting (CWE-79) for 14th place of the 188 weakness types named on KEV entries. The four largest, out-of-bounds write (CWE-787, 167), OS command injection (CWE-78, 124), use after free (CWE-416, 108) and path traversal (CWE-22, 98), each have at least three times as many. KEV's own cwes field marks 33: 1 entry carries CWE-89 only in CISA's field and 0 only in NVD's.
  • In this record it was listed faster, and tied to ransomware more often, than the catalogue as a whole. For the 20 SQL-injection entries whose CVE was published after the catalogue began on 3 November 2021, the time from NVD publication to KEV listing has a median of 4.5 days, against 8 days for all 883 KEV entries; 11 of the 20 were listed within a week of publication. CISA marks 10 of the 32 SQL-injection entries (31%) as known to be used in ransomware campaigns, against 361 of all 1,764 (20%) for the catalogue as a whole.
  • The exploited cases are in products defenders run, not only in code they write. The entries come from 24 vendors; the ones with more than one are Fortinet (3), SonicWall (3), Ivanti (2), Progress (2), Sangoma (2) and Sophos (2). By our own classification of each product (a column in the entries file), 19 of the 32 are network or security products, IT management or monitoring tools, or managed file transfer (network or security products 14, IT management or monitoring 4, managed file transfer 1); the rest are phone systems, business applications, content platforms such as Drupal core, WordPress core and Roundcube Webmail, one building-automation tool and one AI developer tool. The year with the most SQL-injection additions is 2026, with 9 so far.

The limits, stated plainly. The NVD share counts only CVEs that have a weakness type assigned; we did not count how many 2026 records have none, so read the 2026 share (0.64%) as a floor, not as evidence of a decline. KEV lists only CVEs with evidence CISA accepts, so it undercounts exploitation of software without CVEs, including most in-house code. KEV's 2021 additions are the catalogue's first load and include old vulnerabilities, so they are not 2021 exploitation. And 20 SQL-injection entries is a small sample for the timing comparison. The snapshot is dated; the script re-runs it.

For someone who writes queries, the record says two things. Parameterised queries remain necessary because SQL injection keeps appearing in shipped products from large vendors, and the record shows those defects being used within days of publication. And the SQL-injection CVEs most worth tracking on a network are in the appliances and management tools at its edge, so they belong on the patch list, not only in code review.

The fix: separate the code from the data

The OWASP SQL Injection Prevention Cheat Sheet lists the defence first and unambiguously: prepared statements with parameterised queries. "Prepared statements force the developer to define all SQL code first and pass in each parameter to the query later." The SQL text is fixed before any value is attached; the value travels to the database as a typed parameter, not as text spliced into the command. The database never parses the value as SQL, so there is nothing for the input to change.

In Python's DB-API this is the difference between two characters of code:

cur.execute("SELECT balance FROM users WHERE name = '" + name + "'")  # defect: the value becomes SQL text

cur.execute("SELECT balance FROM users WHERE name = ?", (name,))       # fix: the value is bound as a parameter

The placeholder style varies by driver (? for sqlite3, %s for psycopg and mysqlclient, named :name for others), but the principle is identical. Do not build the placeholder list by formatting user input into it either; build it from the number of values you have.

There is one thing parameters cannot do, and OWASP is clear about it: bind variables work for values, not for identifiers such as table or column names. When a query needs a dynamic column or table, the cheat sheet's guidance is that "ideally those values come from the code and not from user parameters", and if user choice really must select a column, validate it against an allow-list of known-good names before it goes near the query. OWASP calls a design that puts user values into table or column names "a symptom of poor design" that warrants a rewrite. Escaping is listed last and described as "fragile"; it cannot "guarantee that this option will prevent all SQL injections in all situations", so it is a fallback, not a plan.

Two supporting controls sit behind the primary fix. Least privilege, from CWE-89's environment-hardening mitigation, means the account the application connects with can read and write only what it needs, so an injection that does slip through cannot drop tables or read other schemas. Allow-list input validation catches malformed input early and documents intent, though OWASP notes that "proper output encoding, escaping, and quoting" and, above all, parameterisation are what actually prevent injection; validation is defence in depth, not the defence.

A test that proves the fix

A fix you cannot test tends to regress. The listing sql-injection-for-people-who-write-queries.py builds a throwaway in-memory SQLite database and runs the same lookup two ways against a set of hostile-looking inputs, then asserts that the parameterised path returns only exact matches and never widens.

python code/sql-injection-for-people-who-write-queries.py

Its output, one line per probe, shows the two paths side by side:

input                 concatenated                            parameterised
'alice'               [('alice', 'alice@example.org')]        [('alice', 'alice@example.org')]  ok
"o'brien"             [('<sql error>', 'near "brien": ...')]   []  ok
"alice' OR '1'='1"    [('alice', ...), ('bob', ...)]           []  ok
"alice'; --"          [('alice', 'alice@example.org')]         []  ok
'%'                   []                                       []  ok

Two rows carry the lesson. The o'brien row is a real surname with an apostrophe: the concatenated query throws a syntax error, which means the same defect that lets an attacker in also breaks on ordinary honest data, so "it works in testing" was never evidence of safety. The alice' OR '1'='1 row is the tautology: concatenation returns every row, while the parameterised query returns nothing, because it looked for a user literally named alice' OR '1'='1 and there is none. The script exits non-zero if the parameterised path ever returns anything but an exact match, so you can drop it into a test suite: point its lookup_safe at your real query function and keep the assertion.

Detection and fix

  • Make parameterised queries the only way values enter SQL in your codebase, and treat any string-built query as a defect to fix, not a style preference.
  • For dynamic table or column names, use an allow-list of known identifiers from your code; never let a request choose an identifier directly.
  • Run the application's database account under least privilege so a missed spot cannot become a full compromise, and reserve schema-changing rights for migrations, not the app.
  • Add a regression test in the shape of the shipped script for the query functions that touch user input, so a future concatenation fails the build.
  • Use static analysis to flag string-built queries; recent evaluations of automated detectors show they help but miss cases, so they supplement the parameterisation rule rather than replace it.

The limitation to state plainly: parameterised queries stop SQL injection, not every injection. The same class of defect, untrusted input reaching an interpreter that mixes code and data, appears in OS command construction, LDAP filters, and template engines, and each has its own parameterised or context-aware fix. The habit to carry across all of them is the one this article is about: never build the program out of the input.

Update, 30 October 2026: added "SQL injection in the exploited record", counts from the NVD and CISA's Known Exploited Vulnerabilities catalogue, with the script and data behind them. The rest of the article is unchanged.

Everything on this site is written for defenders and for people securing systems they own or are authorised to test. It describes how attacks work so they can be recognised and closed; it is not a guide to accessing anyone else's systems.

Sources

  1. OWASP, "SQL Injection Prevention Cheat Sheet"
  2. MITRE, "CWE-89: Improper Neutralization of Special Elements used in an SQL Command"
  3. OWASP, "Top 10:2021 A03 Injection"
  4. CISA, "Known Exploited Vulnerabilities Catalog" (JSON feed, catalogue version 2026.10.29, read 2026-10-30)
  5. NIST, National Vulnerability Database "CVE API 2.0" (read 2026-10-30)