How SQL Injection Attacks Exploit Vulnerable Queries — Patterns and Real-World Examples

UPI Study › Courses › Database Programming › Free lessons › Lesson 12.3 Free with a free account

How SQL Injection Attacks Exploit Vulnerable Queries — Patterns and Real-World Examples

Database Programming · Chapter 12: Database Security and AuditingSection 12.3 · lesson 72 of 769 min · free with a free account

← Securing Databases with SQL: Techniques and ExamplesNext lesson: Defending Against SQL Injection — Parameterized Queries, Input Validation, and Best Practices →

A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →

Earn 3 college credits for Database ProgrammingRecommended for credit by NCCRS · Computer Science 381 · self-paced · one payment, lifetime access

In this lesson

See how concatenated input changes query structure in common injection patterns.

  • Explain how string concatenation lets input change a query's structure
  • Recognize tautology, comment, UNION, blind, stacked and second-order injection
  • Describe what real SQL injection incidents show about weak query boundaries
  • Review code for concatenated SQL, revealing errors and excessive account rights

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (999 words). Read along, or search it.

Opening Scenario

A City Search That Returns Everybody

Leo Park develops the search page at fictional Lantern Books. A city search should return matching customers, yet one unusual input returns everybody. The database has followed the statement it received. Where did the application's intended filter disappear? We will inspect complete statements in a disposable local database, so the difference is visible in real results.

Sandbox Setup

Fictional Customers in an Isolated File

This setup retains the course's customer identifiers, cities, and points. The product subset contains Database Basics and Notebook. These are fictional teaching records, in an isolated shop file. Foreign-key enforcement is enabled before any transaction. Run the setup with the real SQLite shell. It creates the tables without printing a result set. The application would normally construct a query elsewhere. Here, the editor will show the exact SQL text that construction produced.

Intended Query

Searching Customers by City

The intended query says select first name and city from customers, where city equals Pune. The value belongs inside the text comparison. Run it, using header and column display. Those switches change presentation, not which records qualify. Asha, Chen, and Farid appear, because their city matches. The result remains limited to the requested city. Concatenation means joining strings. If application code pastes a visitor's text between quotation marks, that text can escape the intended value position.

Tautology Pattern

An Always-True Condition Removes the Filter

Now the constructed statement contains an empty city value, followed by or, and a comparison that is always true. Run this version. The database parses every character as SQL, because the joined text carries no trustworthy boundary around the visitor's contribution. Matched is six. The always-true comparison is a tautology, so the city condition no longer restricts the result. The application account still determines reachable data. Returning all rows can become a login bypass, if application logic incorrectly accepts that result as authentication.

Comment Pattern

A Comment Marker Hides the Rest

A comment marker can remove a trailing condition from parsing. This local example leaves a city restriction after a double dash, on the same physical line. Run it. SQLite treats the rest of that line as a comment, so the city restriction does not participate. Asha appears. On the following line, order by remains active, because a line comment ends at the newline. SQL Server also supports double-dash comments. MySQL requires whitespace after those dashes, and additionally supports the hash marker. A password test on a later physical line would remain active. The exact constructed statement matters more than an attack-shaped string by itself.

UNION Pattern

Another Table's Data on the Page

A union-based attack adds another select to a result that the page already displays. Our first branch searches for a product name that matches nothing. Run the combined statement. Both branches return two text-compatible columns; the second branch asks for customer names and cities instead of products. Chen and Elena appear under the product-style headings. The display route has carried information from a different table. Column counts must match. SQL Server and MySQL also have type-conversion rules, so a mixed numeric and text example is not portable without checking types. This example uses explicit text conversion. No password table is needed to demonstrate the disclosure.

Blind Injection

Learning From Yes or No Behavior

Blind injection learns from behavior rather than directly displayed records. A page might show an available item, or an empty result. Run these paired predicates. Each asks about the same product, while changing an additional true-or-false condition. The true probe matches one record; the false probe matches none. A difference in page behavior can become a yes-or-no information channel. A time-based variant infers answers through conditional delays. MySQL sleep and SQL Server waitfor delay are different mechanisms; we are not running either. Numeric input is vulnerable too, when pasted into command text. Quotation marks are not required for the added condition here.

Stacked and Second-Order

Extra Statements and Stored Values

Stacked queries send more than one statement in a request. Whether that works depends on the driver, its options, and the permissions of the application account. A semicolon by itself does not establish exploitability. Some APIs reject multiple statements; others allow batches, and single-statement injection remains possible either way. Second-order injection has a different timing. An application safely stores an odd value, then later reads and concatenates it into a new command. The later use is the failure. Data read from the database still needs binding when it becomes input to another query. A stored procedure can contain the same concatenation mistake. The location of the code does not change the boundary the parser needs.

Real Incidents

Heartland, Sony Pictures and TalkTalk

Real incidents show why a small query boundary matters. A federal case involving Heartland and other payment networks described SQL injection as an entry technique. The indictment's figure of more than 130 million card numbers covered several victims. Treating it as a verified Heartland-only total overstates that source. For the Sony Pictures intrusion in 2011, the Justice Department confirmed SQL injection. We do not need attacker-claimed account totals to establish the weakness. For TalkTalk's 2015 attack, the UK regulator reported 156,959 affected customers. Its 2016 fine was £400,000. Outdated software and missed earlier attacks compounded the query flaw.

Code Review

Signs of a Vulnerable Query

During review, look for SQL text joined to variables, including numbers and previously stored values. Trace the complete path into the execution API. Raw database errors can reveal schema details. An account with unnecessary alter, drop, or delegation rights increases the possible consequences. The signal to investigate is a change in command structure. A suspicious-looking string stored as a bound value is still only data.

Quick Check

An Added OR Condition Widens Results

A separate report starts with a Leeds filter, then receives this additional or condition. Predict the matched count for our canonical customers. Pause, and decide. Three matching records. Ben satisfies the city condition; Chen and Elena satisfy the points condition. Run the check to confirm the count. The or combines those qualifying groups, rather than requiring both conditions. One record would ignore the added branch. Six would require a condition that admits every customer, which this threshold does not.

Key Takeaways

Visitor Text Became SQL Syntax

The missing boundary explains Leo's search failure: the visitor's text became SQL syntax. Recognize tautology, comment, union, blind, stacked, and second-order patterns, while checking actual dialect and driver behavior. Trace every value into the command, then inspect result exposure and the application's effective permissions.

About Database Programming at UPI Study

Database Programming (Computer Science 381) is a self-paced online course of 76 video lessons in 12 chapters, from database applications, SQL setup, schema planning and normalization to keys and constraints, data types, filtering and sorting, joins, subqueries, views, indexes, ROLLUP and PIVOT, regular expressions and database security. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Compare: Database Fundamentals vs Database Programming

Why take it here

Why students take Database Programming with UPI Study

Write the SQL behind every appDatabase Programming teaches SQL in MySQL and SQL Server side by side: designing and normalizing tables, keys and constraints, data types, inserting, updating and deleting rows, filtering, grouping, joins, subqueries, views, indexes, transactions, and protecting data from SQL injection. It suits computer science and information technology degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

Database Programming carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About How SQL Injection Attacks Exploit Vulnerable Queries — Patterns and Real-World Examples

What is SQL injection?
SQL injection is an attack in which input pasted into a SQL statement changes the statement's meaning instead of being treated as data. If code joins a visitor's text into a condition such as WHERE city = '...', a crafted value can close the quotation mark and add its own condition. The database cannot tell which characters came from the programmer and which from the visitor, and it runs the result with the application account's permissions.
How does the ' OR '1'='1 injection work?
It turns a filter into an always-true condition, called a tautology. If code places input between the quotes of WHERE city = '', the input ' OR '1'='1 produces WHERE city = '' OR '1'='1', and because '1'='1' is true for every row, the city filter stops restricting the result. If an application treats any returned row as a successful login, the same pattern can bypass authentication. Bound parameters prevent it.
What is blind SQL injection?
Blind SQL injection is when an attacker cannot see query results directly but learns from how the application behaves. By adding true or false conditions, the attacker watches whether a page shows a result or an empty one, turning that difference into yes-or-no answers. Time-based variants infer answers from deliberate delays instead. The defenses are the same as for other injection: bound parameters, minimal account rights and generic error messages.
What is second-order SQL injection?
Second-order SQL injection happens when a value is stored safely at first but is later read back and concatenated into a new query, where it changes that query's structure. The flaw is in the later use, not the original insert. Data that comes from your own database is still untrusted when it becomes part of another statement, so bind it as a parameter every time, including inside stored procedures that build dynamic SQL.

About the Database Programming course

How many college credits is Database Programming?
Database Programming (Computer Science 381) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Database Programming cost and what is included?
$250, paid once, with lifetime access: all 76 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Database Programming take?
It is self-paced with no deadlines. The 76 lessons total about 11 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in Database Programming.

76 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Updated

Database Programming
3 credits · NCCRS
Enroll →