SQL INSERT, UPDATE & DELETE
Learn to change data safely and understand transactions and constraints.
Beginner-friendly explanations, examples, and practice.
1. INSERT
INSERT INTO Students (student_id, name, age, city)
VALUES (101, 'Maya', 19, 'Hamilton');
Specify columns explicitly. This makes statements clearer and safer when table definitions
change.
INSERT INTO Students (student_id, name, age, city)
VALUES
(102, 'Liam', 21, 'Toronto'),
(103, 'Noah', 20, 'Ottawa');
2. UPDATE
UPDATE Students
SET city = 'Burlington'
WHERE student_id = 101;
The WHERE clause is critical. Without it, every row could be updated.
Tip: Before an UPDATE, run the same WHERE condition as a SELECT to confirm the target rows.
3. DELETE
DELETE FROM Students
WHERE student_id = 103;
WHERE determines which records are deleted.
Tip: DELETE without WHERE can remove every row in the table.
4. Transactions
A transaction groups changes into one logical unit. A rollback can undo uncommitted changes.
BEGIN;
UPDATE Accounts SET balance = balance - 100
WHERE account_id = 1;
UPDATE Accounts SET balance = balance + 100
WHERE account_id = 2;
COMMIT;
If something fails before COMMIT, use ROLLBACK where supported.
5. Constraints
Constraint Purpose
PRIMARY KEY Uniquely identifies rows
NOT NULL Requires a value
UNIQUE Prevents duplicates
CHECK Requires a condition
FOREIGN KEY Links tables
CREATE TABLE Users (
user_id INTEGER PRIMARY KEY,
email VARCHAR(255) UNIQUE NOT NULL,
age INTEGER CHECK (age >= 13)
);
6. Safe Change Checklist
Identify the target rows, run a SELECT with the exact WHERE clause, confirm the result, use a
transaction when appropriate, and maintain a recovery strategy.