Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Updating All Rows in a Table3:01 with Andrew Chalkley
Sometimes you need to update values in all rows. Maybe to fix an error or update the status of something. In this video we'll update data!
An update statement for all rows:
UPDATE <table> SET <column> = <value>;
= sign is different from an equality operator from a
WHERE condition. It's an assignment operator because you're assigning a new value to something.
UPDATE users SET password = "thisisabadidea"; UPDATE products SET price = 2.99;
Update multiple columns in all rows:
UDPATE <table> SET <column 1> = <value 1>, <column 2> = <value 2>;
UPDATE users SET first_name = "Anony", last_name = "Moose"; UPDATE products SET stock_count = 0, price = 0;
See all of the SQL used in Modifying Data With SQL in the Modifying Data With SQL Cheatsheet.
Let's remind ourselves of the CRUD acronym and what we know so far.
We know that to create a ruin database, we use the keyword INSERT.
For reading information, we use SELECT.
But how about UPDATE?
Unlike the other two it's not different from the word used in the acronym.
To write an UPDATE statement, you'd write something like this.
UPDATE, the table name, a cue word we haven't used before
SET because we want to set the value of a column, next the column name,
then the equal symbol and then the value.
Now the equal sign in this case is not doing the same thing
as what it would do in a condition in a WHERE clause.
In the WHERE clause, it's the equal to or equality operator.
In the UPDATE statement, it's know as an assignment operator.
This is because we're assigning a new value
to an existing value with a given column name.
Let's see this in action.
Let's first take a look at the patrons table.
Imagine we wanted to give a copy of this database to an outsource developer and
you wanted to anonymize any sensitive data of your patrons
while giving an accurate representation of the user dataset.
Let's use the template from before and change all the last names to anonymous.
The table name is patrons.
The column name is last_name.
And then the value of the text Anonymous.
Let's execute the query.
And it updates all the last names in our table to Anonymous.
But we still have zip codes and
email addresses that could be tracked back to somebody.
Let's update both the email and the zip_code.
To do this, we can use a single statement with each assignment separated like this.
Let's write our statement now.
Let's change the table to patrons.
The first column is email.
The second column is zip_code with the relevant values.
We've got the email as email@example.com and the zip codes set to five 5s.
You need to sign up for Treehouse in order to download course files.Sign up