Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 12/ 160
01. SQL Foundations & Relational Concepts

Updating Records Safely (UPDATE with WHERE)

Update targeted rows safely, preview impact, and avoid the missing-WHERE disaster.

BeginnerUPDATE · WHERE Safety3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

UPDATE changes values in rows that already exist. WHERE picks which rows; leave it out and every row changes.

Think of it like…

Correcting entries in a register with a stamp: you decide which pages to stamp (WHERE) before you start. Stamp without choosing and every page gets the correction.

Where you’ve seen it

Marking one order as shipped: UPDATE orders SET status = 'shipped', shipped_at = now() WHERE id = 501 AND status = 'paid';. The extra status condition makes the update safe if it runs twice or if the order was cancelled meanwhile.

Words you’ll hear

SET
The columns to change and their new values or expressions.
WHERE
Which rows to change. Omitting it changes all rows.
UPDATE … FROM / JOIN
Update rows using values from another table.
Rows affected
The count the database reports; check it matches what you expected.

Visual diagram

Loading interactive diagram

Theory & example queries

Writing the update

SET can assign constants, expressions or other columns. In standard SQL (and PostgreSQL), every expression on the right sees the row's values from before the update, so SET a = b, b = a swaps two columns. MySQL evaluates single-table assignments left to right, so the same statement sets both to b's old value, which is a classic dialect trap.

To update from another table, PostgreSQL uses UPDATE target SET … FROM source WHERE target.id = source.id, and MySQL uses UPDATE target JOIN source ON … SET …. Make sure each target row matches only one source row, or the result is unpredictable. RETURNING (PostgreSQL) shows exactly which rows changed and their new values.

Apply new prices from a staging table (PostgreSQL)Query example
1Input dataStart from the source rows or state that the statement sees.
products before UPDATE
3 rows
products before UPDATE sample rows
idprice
4249.5
84150
1112.5
products after UPDATE
3 rows
products after UPDATE sample rows
idprice
4239.99
84159
1112.5

Product 11 is unchanged because its staged price equals the current price.

2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1UPDATE products p2SET3  price = s.new_price,4  updated_at = now()5FROM6  price_updates s7WHERE8  s.product_id = p.id9  AND p.price IS DISTINCT FROM s.new_price10RETURNING11  p.id,12  p.price;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/12
3OutputInspect the representative rows, affected-row count, plan, or command status.
Rows returned by RETURNING2 sample rows
Rows returned by RETURNING
idprice
4219.99
8412.5

Note: Only products whose staged price differs from the current price are updated. Unchanged and missing staging rows do not appear in the output.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: SET sees old values (except in MySQL); UPDATE … FROM needs one source row per target.

Updating safely

Before an ad-hoc update, run a SELECT with exactly the same WHERE to see which rows and how many will change. Then run the UPDATE inside BEGIN … COMMIT, compare the reported row count with the preview, and ROLLBACK if it's different.

Updating millions of rows in one statement holds row locks and generates a lot of log and (in PostgreSQL) dead row versions. Update in batches by key range or with LIMIT inside a subquery, committing between batches. Adding the expected current state to WHERE (AND status = 'paid') makes updates idempotent and protects against concurrent changes.

Batching a large updateQuery example
1Input dataStart from the source rows or state that the statement sees.
eligible events before batch
3 rows
eligible events before batch sample rows
idarchived
1001false
1002false
1003false
eligible events after final batch
3 rows
eligible events after final batch sample rows
idarchived
1001true
1002true
1003false

The 2026 event remains false because it does not match the cutoff predicate.

2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1UPDATE events2SET3  archived = TRUE4WHERE5  id IN (6    SELECT7      id8    FROM9      events10    WHERE11      created_at < '2025-01-01'12      AND NOT archived13    LIMIT14      1000015  );
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/15
3OutputInspect the representative rows, affected-row count, plan, or command status.
Command status per batch4 sample rows
Command status per batch
rundatabase response
1UPDATE 10000
2UPDATE 10000
3UPDATE 4200
4UPDATE 0

Note: This sample starts with 24,200 eligible events. Stop when the command reports UPDATE 0, which means no remaining rows match the batch's WHERE clause.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

repeated until it updates 0 rows.

Key takeaway: Preview, transaction, check the count, and batch big updates.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1SELECT

Preview the target rows

Run SELECT with the exact WHERE you'll use, and note the row count.

SQL at this step
1SELECT2  COUNT(*)3FROM4  orders5WHERE6  status = 'paid'7  AND created_at < '2026-11-01'
What to watch at this step
Expected
row count
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

UPDATE table SET column = value WHERE condition changes existing rows. The WHERE clause decides which rows change, so without it every row in the table is updated. SET can use expressions and the row's current values (SET stock = stock - 1), and PostgreSQL's UPDATE … FROM or MySQL's UPDATE … JOIN update rows using values from another table.

Why it matters: The missing-WHERE UPDATE is one of the most famous ways to damage production data. Safe habits (preview first, run inside a transaction, check the row count, batch big changes) are what interviewers and senior colleagues look for.

When to reach for it

  • Changing statuses and fields in response to user actions
  • Applying bulk corrections from a staging table
  • Backfilling a new column in batches

When to avoid or be careful

  • UPDATE without WHERE (unless you truly mean every row)
  • Manual production updates outside a transaction
  • Updating millions of rows in a single statement on a busy table

Single UPDATE vs UPDATE … FROM vs batched updates

Single UPDATE with WHERE
Best for: Changing a known, modest set of rows

Strengths: One statement, atomic.

Watch out: Huge updates lock many rows and bloat tables.

UPDATE … FROM / JOIN
Best for: Applying values from another table

Strengths: Set-based, no application loop.

Watch out: Multiple matching source rows give unpredictable results.

Batched updates
Best for: Millions of rows on a live table

Strengths: Short locks, steady load, restartable.

Watch out: Not atomic as a whole; needs a loop or job.

Interview signals & numbers to know

When this topic comes up

  • “I accidentally updated every row”
  • “Update prices from this spreadsheet”
  • Backfills
  • UPDATE with JOIN
  • Idempotent operations

Benchmarks & rules of thumb

0 -
rows protected when WHERE is missing
10,000 -
a common batch size for large updates
1 -
source row allowed per target in UPDATE … FROM

Common mistakes & follow-ups

Common interview mistakes

  • Running UPDATE users SET email_verified = true and verifying every user.
  • Writing SET a = b, b = a in MySQL and expecting a swap.
  • Joining to a source table with duplicate keys in UPDATE … FROM, so the value applied is arbitrary.

Likely interviewer follow-ups

  • How do you update a table using values from another table?
  • How would you safely run a manual UPDATE in production?
  • How would you update 50 million rows without locking the table for hours?
Interview tip: Describe your safety routine (preview, BEGIN, check the count, COMMIT) before showing the syntax. It's the habit interviewers want to hear about.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Updating Records Safely (UPDATE with WHERE) with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Inserting Records (INSERT INTO, Single vs Multi-Row Inserts)
Next topic
Deleting Data (DELETE vs TRUNCATE vs DROP)