Updating rows with UPDATE #
The UPDATE statement changes the values of existing rows:
UPDATE table_name
SET
column_1 = new_value_1,
column_2 = new_value_2
WHERE
condition;
table_name: The table to update.SET: Lists the columns to change and their new values.WHERE condition: Chooses which rows get updated.
If you leave out WHERE, the UPDATE statement changes every single row in the table. This is one of the most common (and most dangerous) mistakes in SQL, so always double check your WHERE clause before running an UPDATE.
Exercise #
We have already created a table products with the columns id, name, category, and price. Write a command that updates the product with id 7 (Notebook) so its price is 4.25, without changing any other product.
Tests #
- The product with
id7now has apriceof4.25. - Every other product's
priceis unchanged.
Solution
UPDATE products
SET
price = 4.25
WHERE
id = 7;
Basic Data Retrieval
Filtering Data
Aggregating Data
Joining Tables
Creating and Managing Tables
Transactions and Data Integrity