6. MySQL: UPDATE Statement

6. MySQL: UPDATE Statement

In this blog, we will learn to update the data in MySQL tables using MySQL's provided UPDATE statement. The UPDATE statement is a DML (Data Manipulation Language) statement used to modify existing records in a table.

It allows you to change the values of one or more columns in a single statement rather than making multiple separate statements to update each column individually.

Points To Remember:

  • It is essential to test and ensure that the update statement works as expected before using it in production. An update statement can cause data loss if misused or without proper backup or testing.

  • So to avoid it, at least on a minor scale in our database, ALWAYS use the WHERE clause; if you don't, it will update all the values in the column.

  • While playing around, if you delete something, don't be worried or demotivated; use SET autocommit = 0 BEFORE USING THE UPDATE STATEMENT in a query. It will help with rolling back the changes. I can't promise the same with industry-level projects.

TheUPDATE Statement:

The UPDATE statement is used to modify the existing records in a table.

Syntax:

UPDATE table_name
SET column_1 = value_1, column_2 = value_2, column_3 = value_3...
WHERE condition;

Example:

We will try to update the 'last_name' of a customer whose customer id is 100.

First, let's check what value the 'last_name' of that specific customer holds before we run the query.

SELECT customer_id, first_name, last_name
FROM customer
WHERE customer_id = 100;

Output

Now, let's run the updation query.

UPDATE customer
SET last_name = 'LOVES SQL' 
WHERE customer_id = 100;

Now, let's check the updated entry:

select customer_id, first_name, last_name
from customer 
WHERE customer_id = 100;

Output:

Note:

  • You can also use a variety of comparison operators in the WHERE clause to update multiple rows at once.

  • MySQL also has the REPLACE INTO statement, which will insert a new row if the primary key does not exist or update the existing row if it does exist.

So here we have covered a simple example of the UPDATE Statement. I would suggest you play around more with this.

More on Delete and rollback in the next blog.

To see more examples, you can always refer w3 schools; it has always been my go-to website to understand things.

References: w3schools.com/mysql/default.asp

*****All the outputs provided are a snippet of the actual result.