In this tutorial, we will focus on the SQL UPDATE
statement, a powerful tool that allows you to modify existing records in a table. We will learn how to use conditions to select specific records to update, and how to assign new values to the fields of the selected records.
By the end of this tutorial, you will:
UPDATE
statement.This tutorial assumes you have a basic understanding of SQL, including how to write SELECT
statements and how to work with tables.
The SQL UPDATE
statement is used to modify existing records in an SQL database. The basic syntax is:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
UPDATE table_name
: This tells SQL which table to update.SET column1 = value1, column2 = value2, ...
: This sets the new values for the columns that you want to update.WHERE condition
: This is the condition that determines which records to update. If you omit the WHERE clause, all records will be updated!Best Practice: Always use a WHERE clause with an UPDATE
statement to avoid updating all the records in your table!
Let's consider an example where we have a students
table with columns id
, name
, age
and grade
.
id | name | age | grade |
---|---|---|---|
1 | Alice | 20 | 88 |
2 | Bob | 21 | 85 |
3 | Charlie | 22 | 90 |
UPDATE students
SET grade = 95
WHERE id = 1;
This will change Alice's grade to 95.
UPDATE students
SET age = age + 1
WHERE grade < 90;
This will increase the age of all students who have a grade less than 90 by 1.
In this tutorial, we've learned how to use the SQL UPDATE
statement to modify existing records in a table. We also learned how to use conditions to select specific records to update.
The next step would be to learn more about advanced SQL queries and functions, including JOINs, GROUP BY, and aggregate functions.
students
table, set the grade of all students named 'Bob' to 92.Solution:
sql
UPDATE students
SET grade = 92
WHERE name = 'Bob';
This will set Bob's grade to 92.
students
table, increase the age of all students who have a grade greater than or equal to 90 by 2.Solution:
sql
UPDATE students
SET age = age + 2
WHERE grade >= 90;
This will increase the age of all students who have a grade of 90 or more by 2.
Exercise 2(B): Now, reduce the grade of the same students by 5.
Solution:
sql
UPDATE students
SET grade = grade - 5
WHERE grade >= 90;
This will reduce the grade of the same students by 5.