Learn SQL  /  Data Modification  /  INSERT, UPDATE, DELETE

INSERT, UPDATE, DELETE

INSERT, UPDATE, and DELETE are SQL's three data-modification statements — together with SELECT, they form the complete toolkit for working with a database.

INSERT — Adding Rows

R Code
INSERT INTO students (id, name, age, score, class)
VALUES (5, "Farid", 24, 81, "A");

-- insert several rows in one statement
INSERT INTO students (id, name, age, score, class)
VALUES
  (6, "Nabila", 20, 73, "B"),
  (7, "Tariq",  26, 95, "A");

UPDATE — Modifying Existing Rows

R Code
UPDATE students
SET score = 90
WHERE name = "Zayn";
⚠ Common Mistake
Forgetting the WHERE clause on an UPDATE changes EVERY row in the table, not just one. Always write and double-check the WHERE clause before running an UPDATE - many people run the equivalent SELECT first to confirm exactly which rows will be affected.

Updating Multiple Columns at Once

R Code
UPDATE students
SET score = score + 5, class = "A"
WHERE score >= 85;

DELETE — Removing Rows

R Code
DELETE FROM students
WHERE score < 60;
⚠ Common Mistake
Just like UPDATE, DELETE FROM students without a WHERE clause deletes EVERY row in the table. This is one of the most common (and most costly) real-world SQL mistakes - always run the matching SELECT first to preview exactly what will be deleted.

Advanced: Safe Testing Pattern with Transactions

🚀 Advanced Example
Wrapping changes in a transaction lets you review the result and undo it with ROLLBACK if anything looks wrong, before making it permanent with COMMIT.
R Code
BEGIN;

DELETE FROM students WHERE score < 60;
SELECT * FROM students;   -- check the result looks right

ROLLBACK;   -- undo everything since BEGIN, OR:
COMMIT;     -- make the change permanent

Key Points

  • INSERT INTO table (columns) VALUES (...) adds one or more new rows.
  • UPDATE table SET column = value WHERE condition modifies existing rows - the WHERE clause is critical.
  • DELETE FROM table WHERE condition removes rows - forgetting WHERE deletes the entire table.
  • Wrap risky changes in BEGIN/COMMIT/ROLLBACK (a transaction) to safely preview before committing.