More SQL Please: UPDATE

pop out tables

users

| id | name_first | name_last | email_address | created_at | active | |----|------------|-----------|---------------------------|---------------------|--------| | 1 | James | Mitchell | jmitchell@email.net | 2023-04-30 09:20:00 | 1 | | 2 | Simon | Chen | simon@sqlanalytics.io | 2023-06-15 14:30:00 | 1 | | 3 | Zara | Amini | zara@aminiconsulting.com | 2023-08-22 11:15:00 | 1 | | 4 | James | Weber | wjames@email.org | 2023-11-05 15:45:00 | 1 | | 5 | Charlotte | Davies | charlotte@zapzoop.io | 2024-02-12 09:49:00 | 0 | | 6 | Marcus | Crawford | marcus@mcrawford.ca | 2024-03-01 09:10:01 | 0 | | 7 | Elena | Moreno | elena@hellocorp.com | 2024-03-12 19:29:11 | 1 | | 8 | Priya | Amini | priya@aminiconsulting.com | 2024-03-24 16:40:00 | 1 |

The UPDATE statement allows you to update existing rows with new values for one or more columns.

An UPDATE will modify every row of the table unless a WHERE clause is provided.

It is not required to provide a WHERE clause but it is highly recommended to avoid accidental updates to the entire table. Some database engines will warn or even prevent you from running a table-wide UPDATE statement.

You can run a SELECT statement with the same WHERE clause to check which rows will be altered with an UPDATE before actually performing the update.

Remember that each example on this website is editable and runnable so you can see the results of your UPDATE by querying the contents of the table, i.e.: SELECT * FROM users;

UPDATE users 
SET email_address = 'james@mitchellfamily.co'
WHERE id = 1;
1 row affected.

You can update multiple columns within the same UPDATE statement.

UPDATE users 
SET active = 0,
    email_address = NULL
WHERE id = 1;
1 row affected.
An UPDATE can use the result of a computation. This example shows using negation logic to toggle the value of a column between 0 and 1 on each update.
UPDATE users 
SET active = NOT active
WHERE id = 1;
1 row affected.

Similar to an INSERT, UPDATE accepts an optional fallback strategy using OR when the update would cause a constraint violation and fail.

Try removing the OR IGNORE clause and run the example again. Notice that the UPDATE now fails with an error.

UPDATE OR IGNORE users
SET id = 1, 
    name_first = 'James', 
    name_last = 'Mitchell', 
    email_address = 'jmitchell@email.net', 
    created_at = datetime('now'),
    active = 1
WHERE id = 2;
0 rows affected.
Some database engines support the RETURNING clause, which will cause the database to return the rows that were updated. You can specify column names to return or * to include all columns.
UPDATE users 
SET email_address = 'james@mitchellfamily.co'
WHERE id = 1
RETURNING id, email_address;
| id | email_address | |----|-------------------------| | 1 | james@mitchellfamily.co |
previous: INSERT home next: DELETE