SQL injection explained: how attackers read your database and how I stop it

TL;DR

Difficulty: Intermediate

SQL injection happens when input a visitor types is glued into a database instruction and becomes part of the command instead of staying data.

  • A single crafted value such as ' OR 1=1 typed into a form can log an attacker in as an admin or read another table entirely.
  • The prize is your customer data, payment fraud leverage, and in the worst case deleted tables and a ransom note.
  • AI assistants reach for the unsafe interpolated pattern because it fills public code, and nobody who pasted it understands why it is or is not safe.
  • The fix in Rails is parameterised queries through ActiveRecord, allowlists for things that cannot be values, Brakeman on every change, Cucumber tests that feed hostile input, and pen testing with SQLmap, Burp Suite and OWASP ZAP before release.

My services page sums up one attack in a line: SQL injection lets attackers read or destroy your entire database. This article opens that line up in full. What SQL injection really is, how a single line of code turns a search box into a way in, what the attacker is after, why AI assistants have made it more common again, and the concrete Rails habits and pen testing I use to keep it out.

The sentence on the product page, in full

On my services page I describe one attack in a single line: "SQL injection: attackers read or destroy your entire database." That line is true, and it is also the understatement of the list. SQL injection is the flaw that has leaked more customer records than any other over the past twenty years, and it is still, in 2026, one of the first things an automated scanner tries against your shop at three in the morning. This article unpacks that one line in full: what SQL injection is, how it actually works, what the person on the other end is really after, why AI assistants have quietly made it more common again, and exactly how I keep it out of the software I build.

I will keep the jargon to a minimum and explain every term the first time it appears. You do not need to write code to follow this. You do need to come away able to ask your developer one or two pointed questions, which is the whole point.

Throughout I use one invented business so the examples stay concrete. Alderwood Supply is a made up online shop in Manchester (alderwoodsupply.example) that sells tools and workwear, takes card payments, holds customer accounts, order history and saved addresses, and runs on Ruby on Rails with a PostgreSQL database. The shop is invented. The code is real and behaves as shown.

What SQL injection is, in plain language

Almost every shop keeps its information in a database: a set of tables, a bit like spreadsheets, holding customers, orders, products and prices. To fetch anything from that database, the application sends it a short instruction written in a language called SQL, short for Structured Query Language. A typical instruction reads almost like English: "select the email and the password hash from the customers table where the id equals 42".

Here is the problem in one idea. The instruction and the thing you searched for travel to the database together, as one piece of text. If the application builds that text by gluing the customer's typed input directly into the middle of the instruction, then a customer who types the right characters is no longer filling in a search box. They are writing part of the instruction. They have crossed the line from data (the thing being looked for) into code (the thing doing the looking). That crossing is SQL injection.

It helps to picture a form letter. Imagine a clerk who writes database instructions by hand, leaving a blank for the search term: "find the order where the reference is ______". An honest customer writes a reference number in the blank. A dishonest one writes a reference number, then a full stop, then a brand new sentence of their own: "and also send me every password in the building". If the clerk reads the whole thing back to the database as one instruction, the database obeys all of it. The database is not broken. It did exactly what the text told it to do. The fault is that untrusted input was allowed to become part of a trusted command.

How the attack actually works, with a worked example

Let me show the mistake and then the fix, because the two sit one line apart and the difference is the entire article.

Alderwood Supply has a login form. Behind it, suppose an inexperienced version of the code builds the lookup by pasting the email and password straight into the SQL text:

# DO NOT do this. Input is glued straight into the SQL.
email = params[:email]
password = params[:password]
User.where("email = '#{email}' AND password = '#{password}'")

The #{...} is Ruby string interpolation: it drops whatever the visitor typed into the middle of the string. On a normal login that produces a sensible instruction. Now watch what happens when someone types this into the email box instead of an address:

' OR 1=1 --

The instruction that reaches the database becomes, in effect, "find a user where the email is blank OR 1 equals 1". One always equals one, so the condition is true for every row. The two characters at the end, a dash dash, start a comment in SQL, which tells the database to ignore the rest of the line, including the password check. The query now returns the first user in the table, very often an administrator, and the attacker is logged in without ever knowing a password. No tool was needed. They typed a sentence into a box.

That is the simplest form. The dangerous forms do not stop at logging in. By injecting further fragments, an attacker can ask the database to attach a second query that reads from another table entirely, so a product search quietly returns the contents of the customers table. Where the page shows no results directly, they fall back to what the trade calls blind injection: they ask the database a true or false question ("is the first letter of the admin password an a?") and read the answer from whether the page loads slower or returns a subtly different result, one character at a time. It is slow for a human and instant for a script.

The fix is almost dull. You never build the instruction by gluing input into it. You send the instruction and the values to the database separately, and you let the database treat the values as nothing but values. In Rails this is the normal way to write a query, which is the happy part of the story:

# Safe. The value is sent separately and can never become code.
User.where(email: params[:email])

# Also safe, when you need a condition written out: use a placeholder.
User.where("email = ?", params[:email])

The ? is a placeholder. ActiveRecord, the part of Rails that talks to the database, sends the instruction with the placeholder and the value params[:email] down a separate channel. The database slots the value into the placeholder after it has already understood the instruction, so there is no way for the value to change what the instruction means. Type ' OR 1=1 -- into that second form and the database looks, very sincerely, for a user whose email address is literally the four words ' OR 1=1 --. It finds nobody. The attack has become an ordinary failed search.

This is the heart of the defence, and it has a name worth knowing: a parameterised query, sometimes called a prepared statement. The instruction is fixed in advance. The values are passed as parameters. Data never gets to be code.

What the attacker is actually after

It is tempting to think of this as vandalism, but almost nobody injects SQL for fun any more. There is money at the end of it, and it arrives by a few well worn routes.

The first is the customer database itself. Names, email addresses, order histories and password hashes have a resale value, and a dump of a live shop's customers is a product sold on criminal markets. If any of your customers reused their shop password on their email or their bank, which a large share of people do, your leak becomes their problem too.

The second is card and payment fraud. A modern shop should never store full card numbers, and if you use a reputable payment provider you do not. But order records, billing addresses and partial card data are enough to make phishing messages that look convincing, because they quote a real recent order. The leak funds the next scam.

The third is leverage. Once an attacker can read the database, they can usually also change it: grant themselves an admin account, alter prices, or, at the destructive end, delete tables and leave a ransom note. The line on my services page, "read or destroy your entire database", is not rhetorical. A single successful injection on an unguarded shop can do both.

A breach scenario for Alderwood Supply

Picture a Saturday. An automated scanner, not a person, crawls thousands of shops looking for a search box that mishandles a stray quotation mark. It finds Alderwood's product search, which an old piece of code built by interpolation. Over a few hours, with no human watching, the script reads the customers table one page at a time: 18,000 rows of names, emails and hashed passwords. On Monday the data is for sale. Alderwood's first sign of trouble is a wave of customers reporting phishing emails that quote their real order numbers. Now it is not only a security incident. Under the UK General Data Protection Regulation it is very likely a reportable personal data breach, with a seventy two hour clock, the Information Commission to notify, and every affected customer to tell. The repair costs a week of work. The lost trust costs more, and lasts longer.

None of that needed a sophisticated attacker. It needed one line of code that glued input into a query, and nobody checking for it.

How AI has quietly raised the risk

For a few years it looked as though SQL injection was in slow retreat, because mature frameworks like Rails make the safe way the easy way. Then coding assistants arrived, and a lot of software is now written by people describing what they want to a model and pasting back whatever it produces. That has pushed the risk the wrong way, for reasons specific to this attack.

An assistant is trained on an enormous pile of public code, and public code is full of the unsafe pattern. String interpolation into SQL is shorter, reads naturally, and appears in countless old tutorials and forum answers. When you ask a model to "search products by name" or "build a report with a sortable column", the interpolated version is a very plausible thing for it to suggest, because it has seen it ten thousand times. The safe version and the unsafe version look almost identical on the screen. The dangerous character is a single quotation mark that is present in one and absent in the other. A reviewer skimming the code, or a founder who cannot read it at all, will not catch that.

The measured picture backs this up. Veracode's 2025 GenAI Code Security Report found that AI generated code contains about 2.74 times more vulnerabilities than code written by people, and that across its test tasks some 45% of AI generated samples introduced a weakness from the OWASP Top 10, the industry's standard list of the most serious web flaws, with injection high on that list12. Ox Security's 2025 analysis of more than three hundred repositories found the same ten anti patterns recurring in 80% to 100% of the AI generated code it examined3. A 2026 study of more than 304,000 commits found that 24.2% of the issues AI introduced were still unresolved later, meaning they were not caught and quietly shipped4. Georgetown's Center for Security and Emerging Technology reached a similar conclusion in 2024 in its work on the cybersecurity risks of AI generated code, as did CrowdStrike's 2025 research56.

There is a second, quieter effect, and it worries me more than any single figure. When a model writes the query and a human pastes it in, nobody in the building understands why it is safe, or whether it is. The code is a black box the moment it lands. There is no test pinning the behaviour, no person who can explain the decision, and when the next assistant edits the same file six months later it may reintroduce the interpolated version and no one will notice. SQL injection thrives in exactly that gap, because the unsafe and the safe versions are a single character apart and both run perfectly on the happy path. The flaw only shows itself when someone types a quotation mark on purpose.

How I defend against it

My defence is not a single trick. It is a set of habits that together make the unsafe pattern hard to write, easy to catch, and impossible to ship quietly. Here is what I actually do on a Rails and Solidus build.

Parameterised queries, always, and never string interpolation into SQL. This is the foundation and everything else is a backstop for it. I use ActiveRecord's own methods, where(email: value), find_by, and friends, which parameterise for you. When I need to write a condition out by hand, I use placeholders and named parameters, never interpolation:

# Named placeholders read well and stay safe.
Order.where("total_cents >= :min AND placed_on >= :since",
            min: 5000, since: 30.days.ago)

The Rails security guide is explicit that passing a string built from untrusted input to a query method is where injection comes from, and it documents exactly which query methods are safe7. There is even a dedicated reference, rails sqli, that catalogues the precise spots in ActiveRecord where a string is treated as raw SQL, so a developer knows which few methods demand care8. I treat those spots as a short, memorised danger list.

Allowlists for anything that cannot be a value. Placeholders protect values, the things in a WHERE clause. They do not protect the structure of a query, such as the name of the column you sort by, because a column name is not a value. So when a page lets the customer choose a sort order, I never pass their text to the database. I check it against a fixed list of permitted columns and reject anything else:

SORTABLE = { "newest" => :created_at, "cheapest" => :price_cents }
column = SORTABLE.fetch(params[:sort], :created_at)
Product.order(column)

The customer's input selects from a list I wrote. It never reaches the database as text. This closes the one gap that placeholders leave open.

Strong parameters at the door. Rails makes you declare, for every form, exactly which fields you will accept. That stops a different but related abuse, mass assignment, where an attacker adds an unexpected field such as admin=true to a form submission. It is not SQL injection, but it lives in the same family: never trust that the input you received is the input you designed for.

Static analysis on every change. I run Brakeman, a scanner built for Rails, on every pull request and on a weekly schedule. Brakeman reads the code without running it and flags SQL injection with high confidence wherever untrusted input reaches a query as a string. The fix is usually one line, a placeholder in place of interpolation, and the warning disappears. A build with an unresolved high confidence warning does not ship. I wrote about this routine in depth in security for a Rails shop.

Behaviour tests that lock the defence in. A fix you cannot prove is a fix you will lose. For every query that handles input, I write a test that feeds it a hostile string and asserts the sane result. In plain language, using Cucumber scenarios a client can read:

Scenario: a search term with SQL characters is treated as text, not code
  Given a customer named "Dilraj" exists
  When I search products for "' OR 1=1 --"
  Then I see no products
  And every customer record is still private

That scenario fails loudly if anyone, human or assistant, ever rewrites the query the unsafe way. The attack becomes a test that must stay green forever. The conversation that turns a worry like this into an executable scenario is the subject of behaviour driven development and the Cucumber guide.

Pen testing before release, with the attacker's own tools. Before a shop goes live, and on a schedule after, I test it the way an attacker would, from a Kali Linux machine, the standard toolkit for this work. I drive the forms through Burp Suite and OWASP ZAP, which sit between the browser and the shop and let me bend every request, and I point SQLmap, the specialist SQL injection tool, at every input that touches the database. If any field can be injected, SQLmap finds it in minutes, which means I find it before anyone else does. The standards I test against are the OWASP Top 10 and the more detailed OWASP Application Security Verification Standard, which I explain in the OWASP ASVS article.

Why testing and pen testing make this insurable work

There is a difference between software that has not been attacked yet and software that has been shown to withstand an attack. The first is a hope. The second is evidence.

Everything above produces evidence. The Brakeman report is a file with a date on it. The Cucumber scenario is a sentence a non technical owner can read, sitting in a test suite that runs on every change and blocks the release if it fails. The pen test is a record of the exact attacks that were tried and did not work. Taken together they turn "I think it is secure" into "here is what we tried, here is what held". That is the kind of statement an insurer, an auditor or a serious customer can actually rely on, and it is the kind of statement a black box of AI generated code can never make.

It matters just as much that the code is mine, owned and readable, not a pile of suggestions nobody can explain. When a flaw is reported against Rails or a library next year, I can find every place it touches, because the code follows the framework's patterns rather than fighting them. Every path that handles input has a test with its name on it. Nothing important happens in a corner no one understands. That is the quiet promise under the whole approach: the defence is not a clever line of code, it is the fact that a person stands behind every query and can prove it is safe.

A short honest close

SQL injection is old, well understood, and almost entirely preventable. The safe way in Rails is also the easy way, which is the good news. The bad news is that the easy way is one quotation mark away from the dangerous way, that AI assistants reach for the dangerous way more often than people think, and that the gap only shows itself when someone goes looking. The answer is not fear. It is a handful of durable habits: parameterise every query, allowlist what cannot be a value, scan on every change, write the hostile input into a test, and attack your own shop before anyone else does.

If you are not sure which side of that quotation mark your own shop is on, that is a reasonable thing not to know, and a quick thing to find out together. In the free workshop we take one real form on your site and trace exactly what happens to what a visitor types, from the box to the database and back. No slides, no hard sell, just a clear answer. The first two weeks of any work that follows are on me.

If you are not sure whether your own shop handles what visitors type safely, book the free workshop: we take one real form and trace exactly what happens from the box to the database and back, and the first two weeks of any work that follows are on me.

Sources

  1. 1.

    Veracode, 2025 GenAI Code Security Report, Veracode, 2025, https://www.veracode.com

  2. 2.

    OWASP, Top 10:2021, A03 Injection, https://owasp.org/Top10/A03_2021-Injection/

  3. 3.

    Ox Security, analysis of more than 300 repositories of AI generated code, Ox Security, 2025, https://www.ox.security

  4. 4.

    2026 study of more than 304,000 commits reporting that 24.2% of issues introduced by AI remained unresolved, 2026

  5. 5.

    Center for Security and Emerging Technology (CSET), Georgetown University, Cybersecurity Risks of AI Generated Code, 2024, https://cset.georgetown.edu

  6. 6.

    CrowdStrike, research on vulnerabilities in AI generated code, CrowdStrike, 2025, https://www.crowdstrike.com

  7. 7.

    Ruby on Rails Guides, Securing Rails Applications, SQL Injection, https://guides.rubyonrails.org/security.html#sql-injection

  8. 8.

    Rails SQL Injection Examples, https://rails-sqli.org/

Shelter

I’m running the London Marathon for Shelter. Sunday 25 April 2027

My personal fundraiser. Shelter, the National Campaign for Homeless People Limited, registered charity 263710 (England and Wales) and SC002327 (Scotland), registered with the Fundraising Regulator.