Free SQL Course / Lesson 7 of 10

SQL INSERT, UPDATE, DELETE, and Transactions

Change records deliberately, inspect affected rows, and protect multi-step operations with transactions.

Lesson 7: Make changes inside a safe transaction

Practice data changes on a development database first. Use explicit column names, narrow predicates, and parameterized statements from application code.

BEGIN;
UPDATE orders
SET status = 'shipped'
WHERE order_id = 1042
  AND status = 'paid'
RETURNING order_id, status;
-- COMMIT after checking the returned row; otherwise ROLLBACK.

Data-change statements

StatementPurposeExample
INSERTAdd rows with named columns.INSERT INTO customers(name,email) VALUES ('Ada','ada@example.com');
INSERT multipleAdd several rows in one statement.VALUES ('A','a@example.com'), ('B','b@example.com')
INSERT SELECTInsert the result of a query.INSERT INTO archive_orders SELECT * FROM orders WHERE created_at < DATE '2020-01-01';
RETURNINGReturn affected rows in PostgreSQL.INSERT INTO items(name) VALUES ('Pen') RETURNING id;
UPDATEChange selected rows.UPDATE products SET price=price*1.05 WHERE category_id=3;
DELETERemove selected rows; check the WHERE clause.DELETE FROM sessions WHERE expires_at < CURRENT_TIMESTAMP;
ON CONFLICTPostgreSQL UPSERT for a unique key.ON CONFLICT (email) DO UPDATE SET name=EXCLUDED.name
BEGINStart a transaction block.BEGIN;
COMMITPersist the transaction's changes.COMMIT;
ROLLBACKDiscard changes in the current transaction.ROLLBACK;

Safe change checklist

  1. Run a SELECT with the same WHERE clause and confirm intended rows.
  2. Use a transaction when the operation has multiple dependent steps.
  3. Check row counts and RETURNING results before commit.
  4. Use foreign keys and unique constraints to prevent invalid state.
  5. Use prepared statements for data supplied by users.

Progress stays in this browser.