Updating Records in SQL

Tutorial 3 of 5

1. Introduction

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:

  • Understand the syntax and use of the SQL UPDATE statement.
  • Be able to use conditions to select records for updating.
  • Know how to set new values for selected records.

This tutorial assumes you have a basic understanding of SQL, including how to write SELECT statements and how to work with tables.

2. Step-by-Step Guide

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!

3. Code Examples

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

Example 1: Updating a single record

UPDATE students
SET grade = 95
WHERE id = 1;

This will change Alice's grade to 95.

Example 2: Updating multiple records

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.

4. Summary

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.

5. Practice Exercises

  1. Exercise 1: In the 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.

  1. Exercise 2(A): In the 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.