INSERT, UPDATE, DELETE and Transactions
Add rows with INSERT, change them with UPDATE, remove them with DELETE, and use WHERE checks and transactions so a typo never wipes out real data.
Welcome back!
Step 1 of 15Learn
Adding rows with INSERT
INSERT INTO adds new rows to a table. List the columns, then the values in the same order:
INSERT INTO customers (customer_id, name, city, email)
VALUES (6, 'Noah Grant', 'Austin', 'noah@example.com');Columns you leave out get their DEFAULT value, or NULL if there is no default. If customer_id is auto-generated, you'd omit it and let the database assign the next number:
INSERT INTO customers (name, city)
VALUES ('Mia Torres', 'Boston');Mia's email is NULL, because no value was given and the column allows NULL.
You can insert several rows in one statement:
INSERT INTO books (book_id, title, author, genre, price, year, stock)
VALUES
(9, 'Cold Harbor', 'Jo Banks', 'Mystery', 16.00, 2024, 10),
(10, 'Small Data', 'Ana Ruiz', 'Tech', 29.00, 2025, 5);Or insert the result of a query, which is handy for copying or archiving:
INSERT INTO archived_orders (order_id, customer_id, order_date, total)
SELECT order_id, customer_id, order_date, total
FROM orders
WHERE order_date < '2026-02-01';Good habits:
- Always list the columns.
INSERT INTO customers VALUES (...)without a column list depends on the exact column order, and breaks or silently misplaces data when someone adds a column. - Expect constraints to push back. A duplicate primary key, a missing NOT NULL value, a failed CHECK or a foreign key with no match will cause an error. That's the database protecting you.
- Never build SQL by pasting user input into a string. Apps should use parameterized queries, which send values separately from the SQL text. Pasting input directly enables SQL injection, where an attacker types SQL code into a form field to read or destroy data.
Step 2 of 15Practice · True or false
If you insert a row and leave out a column that has no DEFAULT and allows NULL, that column is set to NULL.
Step 3 of 15Note
Step 4 of 15Compare
Gluing text vs. parameterized queries
| Aspect | Gluing user input into SQL | Parameterized query |
|---|---|---|
| Code shape | "... WHERE name = '" + input + "'" | "... WHERE name = ?" plus the value sent separately |
| Input treated as | Part of the SQL command | Plain data, never code |
| Attacker types ' OR '1'='1 | Query returns every user | Searches for that odd name; finds none |
| Verdict | Never do this | Always use this |
Step 5 of 15Learn
Changing rows with UPDATE
UPDATE changes values in existing rows:
UPDATE books
SET price = 19.99
WHERE book_id = 1;The Silent Orbit now costs 19.99. You can change several columns at once and use expressions:
UPDATE books
SET price = price * 1.10,
stock = stock + 5
WHERE genre = 'Tech';That raises Tech prices by 10% and adds 5 to their stock. Note that Quiet Numbers' stock stays NULL, because NULL + 5 is NULL.
Now the most important sentence in this lesson: an UPDATE without a WHERE clause changes every row in the table.
UPDATE books SET price = 19.99; -- every book now costs 19.99This is one of the most common and costly mistakes in SQL. A forgotten WHERE, or a WHERE that matches more than you expected, can overwrite thousands of rows in a fraction of a second.
A reliable safety routine:
- Write the WHERE clause first, as a SELECT. Run
SELECT * FROM books WHERE genre = 'Tech';and check that it returns exactly the rows you mean to change. Here, 2 rows. - Turn the SELECT into the UPDATE, keeping the WHERE clause identical.
- Check the reported row count. Databases tell you how many rows were affected. If you expected 2 and it says 2,000, something is wrong.
- Use a transaction for anything important, so you can undo a mistake. More on that shortly.
Prefer identifying rows by primary key when changing a specific record: WHERE book_id = 1 can only ever match one row, while WHERE title = 'River Road' might match several books with the same title.
Step 6 of 15Practice · Work it out
Using the original books table, how many rows does this statement change? UPDATE books SET stock = 0 WHERE author = 'Leo Park' OR price > 40;
Step 7 of 15Learn
Removing rows with DELETE, and transactions
DELETE removes rows:
DELETE FROM orders
WHERE order_id = 106;The same warning applies, even more strongly: DELETE FROM orders; with no WHERE removes every row. The table still exists, but it's empty. Use the same SELECT-first routine.
Foreign keys may block a delete. Deleting customer 1 fails while orders still reference her, unless the foreign key was defined with ON DELETE CASCADE, which deletes her orders too. That protection exists for a reason; think before you cascade.
Many applications avoid hard deletes altogether and use a soft delete: a column such as is_active or deleted_at that marks a row as removed while keeping it for history and audits.
A transaction groups statements into one all-or-nothing unit:
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE account_id = 1;
UPDATE accounts SET balance = balance + 100 WHERE account_id = 2;
COMMIT;Either both updates happen or neither does. If anything fails in between, or if you change your mind, ROLLBACK undoes every change since BEGIN. Without a transaction, a crash between the two updates could make $100 vanish.
Transactions provide the ACID guarantees: Atomicity (all or nothing), Consistency (constraints hold), Isolation (concurrent transactions don't see each other's half-finished work) and Durability (committed changes survive crashes).
They're also a personal safety net. Start a transaction, run your UPDATE or DELETE, check the result with a SELECT, then COMMIT if it's right or ROLLBACK if it isn't. Note that some tools auto-commit each statement by default, so learn how yours behaves before relying on this.
Step 8 of 15Practice · Diagram
A transaction: all or nothing
Changes inside a transaction stay provisional until you commit. Tap each step.
Your DELETE reports 5,000 rows when you expected 3. Which step should come next?
Tap the shape that answers the question, then press Check.
- BEGIN
Starts the transaction.
- UPDATE / DELETE
Changes are visible to you but not final.
- Check row counts
Did the statement affect the number of rows you expected?
- COMMIT
Makes every change permanent at once.
- or ROLLBACK
Throws away every change since BEGIN, as if nothing happened.
Step 9 of 15Practice · Code challenge · SQL
Code challenge · SQL
The store raises the price of Tech books by 10 %. Write the UPDATE statement.
After your statement runs, the checker reads every book_id and price, so a change to the wrong rows is caught.
The database for this exercise (tables and rows)
CREATE TABLE books (
book_id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
author TEXT NOT NULL,
genre TEXT,
price REAL,
year INTEGER,
stock INTEGER
);
INSERT INTO books VALUES
(1, 'The Silent Orbit', 'Mara Quinn', 'Sci-Fi', 18.00, 2019, 12),
(2, 'Gardens of Salt', 'Leo Park', 'Fiction', 15.50, 2021, 0),
(3, 'Data in Practice', 'Ana Ruiz', 'Tech', 42.00, 2022, 7),
(4, 'Night Ferry', 'Leo Park', 'Mystery', 12.99, 2017, 25),
(5, 'Learning to Cook', 'Sam Odell', 'Food', 24.00, 2020, 3),
(6, 'The Last Signal', 'Mara Quinn', 'Sci-Fi', 21.00, 2023, 9),
(7, 'Quiet Numbers', 'Ana Ruiz', 'Tech', 35.00, 2018, NULL),
(8, 'River Road', 'Jo Banks', 'Fiction', 14.00, 2016, 18);- Result matches the expected table
Step 10 of 15Practice · Put in order
Put these steps in the safest order for deleting old test orders from a production table.
Drag the items, or use the arrow buttons, to put them in order.
- Run the DELETE using the identical WHERE clause and check the row count
- Start a transaction with BEGIN
- Check that the SELECT returns exactly the expected rows
- COMMIT if the count is right, or ROLLBACK if it is not
- Write a SELECT with the WHERE clause that identifies the test orders
Step 11 of 15Note
Step 12 of 15Compare
How much does each command remove?
| Aspect | DELETE ... WHERE | DELETE (no WHERE) | DROP TABLE |
|---|---|---|---|
| Rows removed | Only matching rows | All rows | All rows |
| Table structure | Kept | Kept, empty | Gone |
| Undo inside a transaction | Yes, ROLLBACK | Yes, ROLLBACK | Depends on the database |
| Typical use | Remove specific records | Clear test data (carefully) | Remove a table you no longer need |
Step 13 of 15Practice · Match the pairs
Match each command to what it does.
Tap an answer, then tap the place where it belongs (or drag it there).
- INSERT
- UPDATE
- DELETE
- DROP TABLE
- ROLLBACK
Step 14 of 15Note
Step 15 of 15Practice · What would you do?
What would you do?
You need to raise the price of every Sci-Fi book by $2. You type: UPDATE books SET price = price + 2; and are about to press Enter inside a transaction you just started. What should you do?
Lesson complete!