The UPDATE statement is used to update existing records in a table.
General syntax:
In this part of the tutorial we will use the table Test that has the following structure and data :
-we can see that Mike has no email address and Paul has no id and email address. -so for us to insert an email address that will be on the same row with Mike we will use the "update" command with the "where" clause.
-before we do this create the table and add data to it using the following sql sintax:
Script:(copy and paste this in your mysql terminal)
Now see the result :
So now let's create the update statement that will add an email address to Mike
We can do this using as 'where' reference our ID column
Example:
Check the table
We can see that the table added an email address where ID column is equal to 3.
Now let us add an id and an email address to the row where Name is Paul:
Example:
Great, now check the table.
We can see that Paul got his ID and his EMAIL field in.
Note:
The "set" statement is the one responsible for pointing which columns will be updated and with what values they will receive and the "where" statement will point which is the row/rows will be updated.
Very important
If you omit the "where" clause, all records on that column will be updated!So always use a where clause and double check you update statements before running them.
Example of update statement with no "where " clause:
And let's check the changes made by this statement.
We can see the when we used the "update" statement with no "where" clause all the values of the column ID and EMAIL will receive the values stated in the update statement. Se be aware of updates with no condition clauses they can be dangerous.
There's lot's of update condition clauses types, but for now we will stick with this only. More advanced updates types in the future tutorials.