An UPDATE statement changes rows that already exist in a table. The SET clause names the columns and their new values, and the WHERE clause chooses which rows change:
UPDATE table_name
SET column_name = new_value
WHERE condition;
The examples use a dbo.Students table with StudentID, StudentName, Score, Grade and Status columns. For example, this changes the grade of the student with StudentID 2 to B:
UPDATE dbo.Students
SET Grade = 'B'
WHERE StudentID = 2;
What each part does
UPDATEnames the table to change.SETgives one or morecolumn = valuepairs.WHERElimits the update to matching rows. It is optional, but leaving it out has a large effect, as explained below.
Update more than one column
Separate the assignments with commas:
UPDATE dbo.Students
SET Grade = 'A',
Status = 'Passed'
WHERE StudentID = 1;
Use the current value
The value on the right of = can use the column’s current value. This adds 5 to the score of the student with StudentID 3:
UPDATE dbo.Students
SET Score = Score + 5
WHERE StudentID = 3;
What happens without WHERE
If you leave out WHERE, the statement changes every row in the table:
UPDATE dbo.Students
SET Status = 'Reviewed';
Every student now has Reviewed in Status. A missing WHERE is a common mistake, so it is worth checking the filter before you run any update.
Check before you run it
- Preview the rows. Run a
SELECTwith the sameWHEREclause first to see which rows match:
SELECT StudentID, StudentName, Score
FROM dbo.Students
WHERE StudentID = 3;
- Use a transaction. In SQL Server, put the update between
BEGIN TRANSACTIONand aCOMMIT TRANSACTIONorROLLBACK TRANSACTION. Check the rows, then commit to keep the change or roll back to undo it. - Keep a backup before a large change to important data.
UPDATE and INSERT
UPDATE changes rows that are already in the table. INSERT adds new rows. If you need to add a student rather than change one, what is an insert statement explains that form.
Different values for different rows
Sometimes each row needs a value that depends on its own data. In that case, put a CASE expression in the SET clause. The pattern is explained in the guide to a case statement in update query in sql server.
The basic form of UPDATE works in most SQL databases. SQL Server and other systems add their own options, so check the documentation for the system you use.