SQL & Databases·Data in practice

Changing data safely

Insert, update and delete without losing rows you meant to keep.

Beginner 14 min read Lesson 15 of 480 Challenge included
What you will be able to do
  • Write targeted UPDATE and DELETE
  • Wrap changes in a transaction
  • Preview the affected rows first

A data change is only as safe as its WHERE clause. Preview the rows, run the statement inside a transaction and commit only after checking the count.

write.sqlSQL
BEGIN;

INSERT INTO lessons (id, course_slug, title, minutes, level)
VALUES (11, 'sql', 'Transactions', 16, 'Advanced');

UPDATE lessons
SET minutes = minutes + 2
WHERE course_slug = 'sql';

SELECT id, title, minutes
FROM lessons
WHERE course_slug = 'sql';

ROLLBACK;
  1. 01
    Select first

    Run the same WHERE with SELECT and count the rows.

  2. 02
    Begin

    Start a transaction so the change can be undone.

  3. 03
    Change

    Run INSERT, UPDATE or DELETE with the narrowest WHERE.

  4. 04
    Verify

    Select the affected rows and check the counts.

  5. 05
    Commit or roll back

    Commit when correct; roll back on any doubt.

Your turn

Insert, update and roll back

Medium

In one transaction, insert a lesson called Indexes with 13 minutes, add 1 minute to it, then roll back.

SQL · starter
BEGIN;

-- insert and update here

ROLLBACK;
Check your understanding before moving on.
Knowledge checkQuestion 1

What does ROLLBACK do inside a transaction?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Next: Project: course report
Lesson 15 of 480 · 0% of course