SQL Tutorial menu

SQL UPDATE

UPDATE changes data that is already in a table.

UPDATE Syntax

Example

sql
UPDATE table_name
SET column1 = value1, column2 = value2
WHERE condition;
  • SET says which columns get which new values
  • WHERE says which rows to change

Update One Row

Hamza Raza has now chosen the Digital Marketing course (id 4):

Example

sql
UPDATE students
SET course_id = 4
WHERE id = 5;
Output
1 row updated.

Example

sql
SELECT name, course_id FROM students WHERE id = 5;
namecourse_id
Hamza Raza4

Using the id in WHERE is the safest way to change exactly one row, because each id is unique.

Update Several Columns

Separate the columns with commas. Bilal moved to Lahore and his marks were corrected after a recheck:

Example

sql
UPDATE students
SET city = 'Lahore', marks = 68
WHERE id = 3;
idnamecitymarks
3Bilal AhmedLahore68

Update Many Rows

A WHERE condition can match many rows. The institute decides that every 3-month course will now take 4 months:

Example

sql
UPDATE courses
SET duration_months = 4
WHERE duration_months = 3;
Output
2 rows updated.
idtitleduration_months
1Web Development6
2Python Programming4
3Graphic Designing4
4Digital Marketing4

Use the Old Value

The new value can be calculated from the current value. Here every student from Karachi gets 2 grace marks:

Example

sql
UPDATE students
SET marks = marks + 2
WHERE city = 'Karachi';

Each matching row uses its own current marks, so Ali goes from 78 to 80 and Hamza from 70 to 72.

Warning: Do Not Forget WHERE

If you leave out WHERE, every row in the table is changed:

Example

sql
UPDATE students
SET city = 'Karachi';
Output
6 rows updated.

Now all students live in Karachi, and the real cities are lost.

Before running an UPDATE, first run a SELECT with the same WHERE clause. If it shows exactly the rows you expect, change SELECT ... FROM to UPDATE ... SET. Many tools also let you work inside a transaction, so a mistake can be undone with ROLLBACK.

Quick Reference

GoalStatement
Change one rowUPDATE students SET age = 20 WHERE id = 1;
Change two columnsUPDATE students SET age = 20, marks = 80 WHERE id = 1;
Change matching rowsUPDATE students SET marks = 0 WHERE marks IS NULL;
Change all rowsUPDATE students SET marks = 0; (careful!)

Exercise

Exercise

What happens when you run: UPDATE courses SET duration_months = 5;

Learn SQL with a teacher

Join the Full Stack Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp