SQL UPDATE Command
Learn how SQL Update Command works and update records, while working with PHP and mySQL.
See this table. We name it student.
Update command in SQL is used to change any record in the table. Records are to be manipulated or updated using update command. Conditional update is the most common type of update command used in MySQL also. You are requested to go through the SQL WHERE command before using update command as both are to be used in proper combinations. WHERE will tell the command that which record will be updated and where in row. Here is one simple command. Without using any WHERE command (or without using any restriction) the command will change all the records of the table. So let us start with the simple command. Our table name is student here.
UPDATE student SET class='Five'
This command will change all the records of the table student and will change all the class fields to Five. This is not what is required in common cases so we will be changing records based on some conditions. Now we will change all the class four students to class nine. Our command should selectively update those records for which class is equal to “four” and will update them to “nine”. We will use one where clause along with update command for updating the records.
UPDATE student SET class='nine' WHERE class='Four'
This command will update only those records for which class is equal to ‘Four’. So this way we can update records selectively. Now let us move one more step and change the records selectively based on some value in some other field also. We will change records for which class is equal to ‘Four’ and mark is more than 70. We will promote those students only who has got more than or equal to 70 mark.
UPDATE student SET class='nine' WHERE class='Four' and mark >= 70
This will only change the records for which class=four and mark is more than or equal to 70. We have added two conditions by using AND as a logical operator. This way we can continue with adding more AND combinations to the query. Depending on the logic requirement OR combination can be added to the WHERE clause to UPDATE the records.
UPDATE student SET class='nine' WHERE class='Four' and mark >= 70 and name='javed'
UPDATE student SET class='nine' WHERE class='Four' and mark >= 70 and name like '%javed%'