Lesson 4 of 4
Databases: Lesson 4

SQL Data Manipulation and SQL Injection

Add, update and delete records using INSERT, UPDATE and DELETE. Query multiple tables. Understand SQL injection attacks and how parameterised queries prevent them.

55 minutes Includes SQL injection

Reading data from a database is only half the story. Every time someone signs up for an account, buys something, or cancels a subscription, the database changes. INSERT adds new records, UPDATE modifies existing ones, and DELETE removes them. And all of this must be protected from attackers who know how to abuse SQL itself.

Think about it: In 2012, LinkedIn had 6.5 million password hashes stolen via SQL injection. The attacker did not hack the server - they typed specially crafted text into a form field. The database executed it as a command.
Adding new records
INSERT INTO TableName (field1, field2, ...) VALUES ('val1', 'val2', ...)
Adds a new row to the table. You list the fields you are providing values for, then the values in the same order. String values are enclosed in single quotes; numbers are not.
INSERT INTO Students (StudentID, FirstName, LastName, Age, Year, IsEnrolled, Score)
VALUES (1008, 'Ivy', 'James', 15, 10, TRUE, 76)

This adds one new row: StudentID 1008, Ivy James, 15 years old, Year 10, enrolled, score 76.

Exam angle

The order of values must match the order of fields listed in brackets. If you omit a field from the list, it must either have a default value or be nullable. The primary key must be provided and must be unique - inserting a duplicate primary key will cause an error.

Modifying existing records
UPDATE TableName SET field = value WHERE condition
Changes the value of one or more fields in rows that match the WHERE condition. Multiple fields can be updated in one statement using commas.
UPDATE Students
SET Score = 90, IsEnrolled = TRUE
WHERE StudentID = 1003

Updates Clara Davis's score to 90 and sets her as enrolled. The WHERE clause ensures only her row is affected.

Critical warning: If you omit the WHERE clause from an UPDATE statement, the change applies to every row in the table. UPDATE Students SET Score = 0 would set every student's score to zero. Always include WHERE.
Removing records
DELETE FROM TableName WHERE condition
Removes rows matching the WHERE condition from the table. The deletion is permanent - there is no undo.
DELETE FROM Students
WHERE StudentID = 1006

Removes Frank Green's record from the table. Only the row where StudentID = 1006 is deleted.

Critical warning: DELETE FROM Students with no WHERE clause deletes every single row in the table. The table structure is preserved but all data is gone. Always double-check your WHERE clause before running DELETE.
Exam angle

A common 3-4 mark question asks you to write an INSERT, UPDATE or DELETE statement for a given scenario. Read carefully: if asked to update a teacher's email "for all students in Year 11", the WHERE clause must specify Year = 11. Marks are often lost for missing or incorrect WHERE conditions.

Combining data from two tables

A query can retrieve data from two tables at once by listing both in FROM and specifying how they link in WHERE. This is how foreign keys are used in queries.

Students

StudentIDNameCourseID
1001Alice Smith201
1002Bob Brown202

Courses

CourseIDCourseName
201GCSE Maths
202GCSE CS
-- Return each student's name and their course name
SELECT Students.Name, Courses.CourseName
FROM Students, Courses
WHERE Students.CourseID = Courses.CourseID

The WHERE clause acts as the JOIN condition - it matches the foreign key in Students to the primary key in Courses. Only rows where the IDs match are included. The dot notation (Students.CourseID) specifies which table a field belongs to - required when two tables have fields with the same name.

When user input becomes a SQL command

SQL injection is an attack where malicious SQL code is entered into a form field. If the application inserts user input directly into a SQL query without checking it, the attacker's code becomes part of the query - and the database executes it.

Vulnerable login - how the attack works

The application builds this query using the username field directly:

-- Application code (Python):
query = "SELECT * FROM users WHERE username = '" + username + "' AND password = '" + password + "'"

If username = ' OR '1'='1

SELECT * FROM users
WHERE username = '' OR '1'='1'
AND password = ''

Result: '1'='1' is always true, so this returns all rows. The attacker is logged in as the first user in the database - likely an admin account.

What SQL injection can do

Beyond bypassing login: read all records from any table, delete tables (DROP TABLE), extract usernames and passwords, modify data. It is one of the most common and dangerous web vulnerabilities.

Parameterised queries - the defence

A parameterised query (also called a prepared statement) separates the SQL structure from the user input. The input is never concatenated into the SQL string - it is passed as a separate parameter and treated as plain data, never as SQL code.

-- SAFE - parameterised query (Python example):
query = "SELECT * FROM users WHERE username = ? AND password = ?"
cursor.execute(query, (username, password))

Even if the attacker types ' OR '1'='1, the database looks for a user whose username is literally that string - not a SQL condition. The attack fails completely.

Test yourself

1. A student's score needs to be updated from 67 to 80. Their StudentID is 1002. Which SQL statement is correct?

Correct. UPDATE … SET … WHERE is the correct syntax. The third option is wrong because it has no WHERE clause - it would update every row. INSERT is for adding new rows. MODIFY is not a SQL command.

2. What is the main risk of omitting the WHERE clause from a DELETE statement?

Correct. Without WHERE, DELETE removes all rows. The table structure (fields and data types) remains, but every record is gone. This is a common and catastrophic mistake. Always verify your WHERE clause before running DELETE.

3. How do parameterised queries prevent SQL injection?

Correct. Parameterised queries fix the SQL structure first, then pass user input as a separate parameter. The database treats the input as a data value, not as SQL code. Even if the input contains SQL keywords or quotes, it cannot affect the query structure.
Challenge question

A new student joins Year 10 and needs to be added to the database: Jade King, age 15, enrolled, score 0, CourseID 201. Write the SQL statement, then explain what would happen if you forgot the WHERE clause on a subsequent UPDATE that sets her score to 65.

INSERT INTO Students (StudentID, FirstName, LastName, Age, Year, IsEnrolled, Score, CourseID)
VALUES (1009, 'Jade', 'King', 15, 10, TRUE, 0, 201)
If the subsequent UPDATE is written as UPDATE Students SET Score = 65 without a WHERE clause, every student in the database has their score set to 65 - not just Jade. All original scores are permanently overwritten. This demonstrates why WHERE is mandatory when you intend to update a specific record.
Printable Worksheets

Practice what you have learned

Three levels of worksheet for this lesson. Download, print and complete offline.

Recall
DML Commands Recall
INSERT, UPDATE and DELETE syntax matching. Identify missing clauses and correct syntax errors.
Download
Apply
Multi-table Queries
Write queries joining two tables. Predict the effect of UPDATE and DELETE without a WHERE clause.
Download
Exam Style
Exam-Style Questions
Extended questions on SQL manipulation, injection attacks and parameterised query prevention. Mark scheme included.
Download
Lesson 4 - Databases
SQL Manipulation and SQL Injection
Starter activity
Ask students: "If you wanted to change your password on an app, what happens in the database?" Lead them to realise an UPDATE runs behind the scenes. Then: "If you close your account, what runs?" DELETE. This makes the DML commands feel real before syntax is introduced.
Lesson objectives
1
Write an INSERT INTO statement to add a new record.
2
Write an UPDATE statement to modify existing data.
3
Write a DELETE statement and explain the risk of omitting WHERE.
4
Write a query involving two tables with a linking WHERE condition.
5
Explain what SQL injection is, how it works and how parameterised queries prevent it.
Discussion questions
What would actually happen to a website if an attacker ran DROP TABLE users via SQL injection?
Why is parameterised query different from just checking for single quotes in the input?
Exit tickets
Write a SQL statement to add a new product (ID=501, Name='Keyboard', Price=29.99) to a Products table. [2 marks]
A student's score has changed to 88. Write an UPDATE statement. [2 marks]
Explain what SQL injection is and describe one way to prevent it. [4 marks]
Homework suggestion
Research one real-world SQL injection attack (e.g. TalkTalk 2015, LinkedIn 2012, Yahoo 2012). Describe: what data was stolen, how the attack likely worked, and what the company should have done to prevent it.