← Back to Chapters

MySQL UPDATE

?️ MySQL UPDATE

? Quick Overview

The UPDATE statement in MySQL is used to modify existing records in a table. Use SET to assign new values and WHERE to limit which rows change. Omitting WHERE updates every row.

? Key Concepts

  • UPDATE — changes existing rows in a table.
  • SET — specifies columns and their new values.
  • WHERE — filters rows; omitting it updates every row.
  • Transactions — use them to group updates safely.
  • Test updates on a small dataset or backup before running in production.

? Syntax / Theory

? View Code Example
// Syntax for UPDATE statement
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

? Code Example(s)

? View Code Example
// Update the 'age' of a student named John Doe
UPDATE students
SET age = 23
WHERE name = 'John Doe';
// Update multiple columns for Jane Smith
UPDATE students
SET age = 24, department = 'Science'
WHERE name = 'Jane Smith';

? Live Output / Explanation

What happens when you run these queries

The first query finds rows where name = 'John Doe' and sets their age to 23. The second query updates age and department for rows where name = 'Jane Smith'. If no rows match, zero rows are changed.

✅ Tips & Best Practices

  • Run a SELECT with the same WHERE first to preview affected rows.
  • Use transactions (START TRANSACTION / COMMIT) for multi-step updates.
  • Add indexes on columns used in WHERE for large tables.
  • Use LIMIT cautiously where supported to restrict changes.

? Try It Yourself / Practice Tasks

  • Update the department of a student where student_id = 101.
  • Increase the age by 1 for all students in the 'Science' department.
  • Use a transaction to update two related tables and then roll back to test safety.