Skip to main content

Updating Data with the UPDATE Statement

In this tutorial, we will explore the use of the UPDATE statement in SQL. The UPDATE statement is an essential part of SQL as it allows us to make changes to existing data within our database. With this command, we can modify individual rows or a set of rows in a table.

Before we proceed, it's important to remember that modifying data in a database is a powerful action. It's recommended to always backup your data before executing an UPDATE statement, especially on a production database.

Basic Syntax of the UPDATE Statement

The UPDATE statement is used in combination with the SET and WHERE clauses. The basic syntax is as follows:

UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
  • The UPDATE clause specifies the table where we want to change data.
  • The SET clause indicates the columns we want to modify and the new values we want to assign.
  • The WHERE clause specifies the rows that should be updated. If WHERE clause is not used, all rows in the table will be updated.

Example of the UPDATE Statement

Let's say we have a Students table as shown below:

StudentIDFirstNameLastNameAge
1JohnDoe20
2JaneDoe22
3AliceJohnson19
4BobSmith21

We realize that John Doe's age is actually 21, not 20. We can correct this using the UPDATE statement:

UPDATE Students
SET Age = 21
WHERE StudentID = 1;

After running the above command, our table will look like this:

StudentIDFirstNameLastNameAge
1JohnDoe21
2JaneDoe22
3AliceJohnson19
4BobSmith21

As you can see, John's age has been updated to 21.

Updating Multiple Columns

You can also update multiple columns at once. Let's say Alice Johnson's last name has changed to Williams and her age is now 20. We can update both these columns at the same time:

UPDATE Students
SET LastName = 'Williams', Age = 20
WHERE StudentID = 3;

After running the above command, our table will look like this:

StudentIDFirstNameLastNameAge
1JohnDoe21
2JaneDoe22
3AliceWilliams20
4BobSmith21

In this tutorial, we discussed how to use the UPDATE statement to modify data in an SQL table. It's a powerful tool that can change a single row, multiple rows, or even all the rows in a table. Always remember to use the WHERE clause wisely to avoid updating unintended data.