Skip to content
Back to 50 Concepts
Topic 8 of 50foundationsBeginner

# Topic 8: UPDATE Statements

Mutating column values, multi-column updates, WHERE safety guards, RETURNING, and MVCC tuple versioning.

1. Definition

The UPDATE statement is a DML command that modifies existing column values in one or more table rows matching a search condition.

Relational Invariant:Deterministic relational algebra contract evaluated by the Cost-Based Optimizer.

2. Explain Like I'm 5

Intuitive mental model for beginners

UPDATE is like using white-out and a pen on an existing form. You locate the exact file by ID, erase the old number, and write the new value.

3. Animation & Visual Simulation

Interactive Engine Trace
Interactive Engine Simulation

UPDATE Statements Visual Simulator

Step 1 of 3
SQL>UPDATE users SET balance = balance + 100.00, updated_at = NOW() WHERE id = 42 RETURNING id, balance;Active Input

Step 1: Input & Parsing Stage

Engine Action: Validate SQL syntax and resolve schema metadata for UPDATE Statements
SQL Input

Initiating UPDATE Statements

Schema Catalog

Checking Table Invariants

How the Database Executes This:

The database engine inspects active tables, verifies permissions, and prepares the physical operation.

💡 Form Revision: Cross out the old line, stamp the expiration time on it, and append the new revised record.

4. Real-World Example

An e-commerce customer upgrades their shipping address and receives a confirmation receipt.

Before Update
iduser_idstatus
1011pending
After Update
iduser_idstatus
1011shipped
Relational walkthrough: The order status mutates from pending to shipped in an atomic transaction.

5. SQL Syntax

ANSI SQL / PostgreSQL Dialect
Step 1: Targeted update with WHERE and RETURNING
UPDATE orders
SET status = 'shipped', shipped_at = CURRENT_TIMESTAMP
WHERE id = 101 AND status = 'pending'
RETURNING id, status, shipped_at;
Guards ensure you only transition valid pending orders.
Step 2: Multi-column calculated update
UPDATE accounts
SET balance = balance - 25.00, updated_at = NOW()
WHERE id = 42;
Relative updates prevent overwriting concurrent balance changes.

6. Important Rules & Behaviors

RuleBehavioral Explanation
Mandatory WHERE ClauseAn UPDATE statement without a WHERE clause updates every single row in the table.
Row-Level Exclusive LocksThe database acquires an exclusive row lock on every updated row until COMMIT or ROLLBACK.
Constraint Re-checkAll foreign key, check, and type constraints are validated for updated values.
MVCC non-destructive updatePostgreSQL does not overwrite row bytes on disk; it marks the old tuple dead and writes a new tuple version.
Row-level exclusive lockingUPDATE statements acquire an Exclusive Row Lock (X-Lock) on target rows until the transaction commits.

7. Deep Dive: MVCC: In-Place Overwrites vs New Tuple Versions

Under Multi-Version Concurrency Control (MVCC) in PostgreSQL, an UPDATE does NOT overwrite the old row in place. Instead, it marks the old tuple header (t_xmax = current_tx) and writes a brand new tuple (t_xmin = current_tx) into the page.

-- Behind the scenes in Postgres page:
-- Tuple 1: [xmin: 100, xmax: 105 (expired), data: "pending"]
-- Tuple 2: [xmin: 105, xmax: 0 (current), data: "shipped"]
Caution: Updating indexed columns generates index churn and page bloat until VACUUM cleans old versions.

8. Advantages & Disadvantages

Advantages

  • •In-place transactional state transitions.
  • •Supports mathematical relative increments without client-side state round-trips.
  • •RETURNING clause confirms updated state instantly.

Disadvantages & Trade-offs

  • •Forgetting the WHERE clause accidentally mutates the entire table.
  • •Heavy updates can cause table bloat and high write amplification.

9. Common Interview Questions

Q1.How does an UPDATE physically execute under MVCC in PostgreSQL vs MySQL InnoDB?

In PostgreSQL, an UPDATE is essentially a DELETE + INSERT: the existing tuple’s xmax is set to the current transaction ID, and a completely new tuple version is appended to the page with xmin set to current TX. In MySQL InnoDB, updates modifying non-indexed columns update the row in-place and write the previous version into the Undo Log segment for rollback and MVCC reads.

Q2.What is Heap-Only Tuples (HOT) optimization in PostgreSQL for UPDATEs?

Normally, when a new tuple version is written, every index on the table must be updated with the new tuple pointer (CTID). If an UPDATE modifies ONLY non-indexed columns and the new tuple fits inside the SAME 8 KB disk page as the old tuple, PostgreSQL uses HOT: the old tuple points directly to the new tuple via a page-internal link, completely eliminating index write overhead.

Q3.What is the Lost Update anomaly and how do you prevent it using Optimistic vs Pessimistic Locking?

A Lost Update occurs when two transactions read the same row, compute a new value, and write it back: the second write silently overwrites the first. Pessimistic Locking prevents this using SELECT ... FOR UPDATE (locking the row during read). Optimistic Locking adds a version INT column: UPDATE accounts SET balance = 150, version = version + 1 WHERE id = 1 AND version = 3; if rows_affected is 0, another transaction updated it first and the application retries.

Q4.What happens when two concurrent transactions attempt to UPDATE the exact same row?

The first transaction acquires a row-level Exclusive Lock. When the second transaction tries to update the same row, it is blocked and waits in the lock queue. When the first transaction commits: under READ COMMITTED, the second transaction re-evaluates the WHERE clause on the newly committed row version; under REPEATABLE READ, the second transaction immediately aborts with a serialization failure error.

Q5.How can you UPDATE multiple rows with different values in a single atomic SQL statement?

You can combine UPDATE with a derived table or CTE using VALUES: UPDATE products AS p SET price = v.new_price FROM (VALUES (1, 19.99), (2, 29.99), (3, 39.99)) AS v(id, new_price) WHERE p.id = v.id; This updates hundreds of distinct rows in a single round-trip without loops.

10. Interview-Ready Answer

“The UPDATE statement mutates existing rows matching a filter predicate. Under relational MVCC engines, updates create new row versions while locking updated records until transaction completion.”

11. Quick Test

Scenario Question:

What happens if you run "UPDATE users SET status = 'inactive';" without a WHERE clause?

Select your answer: