Changing data

INSERT, UPDATE and DELETE safely.

SQL
INSERT INTO students (id, name, dept, marks)
VALUES (6, 'Farah', 'CSE', 79);

UPDATE students
SET marks = 80
WHERE id = 6;

DELETE FROM students
WHERE id = 6;

An UPDATE or DELETE with no WHERE changes every row in the table. Run the same condition as a SELECT first, so you can see exactly which rows it will touch.

Transactions

A transaction makes several changes succeed or fail together, as in a money transfer.

SQL
BEGIN;
UPDATE accounts SET balance = balance - 500 WHERE id = 1;
UPDATE accounts SET balance = balance + 500 WHERE id = 2;
COMMIT;

Use ROLLBACK instead of COMMIT to cancel. In application code, always use parameters and never join user input into a query string, which prevents SQL injection.

โ† SubqueriesTables, keys and normalisation โ†’