0
0
SQLquery~5 mins

UPDATE multiple columns in SQL

Choose your learning style9 modes available
Introduction
We use UPDATE to change data in a table. Updating multiple columns lets us change several pieces of information in one go.
When you want to fix or change several details about a person in a contact list.
When you need to update the price and stock of a product at the same time.
When you want to change both the status and the date of an order.
When correcting multiple fields after getting new information from a customer.
Syntax
SQL
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Use commas to separate each column = value pair.
The WHERE clause limits which rows get updated. Without it, all rows change.
Examples
This changes the first and last name of the employee with ID 5.
SQL
UPDATE employees
SET first_name = 'Anna', last_name = 'Smith'
WHERE employee_id = 5;
This updates the price and stock for product number 10.
SQL
UPDATE products
SET price = 19.99, stock = 50
WHERE product_id = 10;
This marks order 100 as shipped and sets the shipped date.
SQL
UPDATE orders
SET status = 'Shipped', shipped_date = '2024-06-01'
WHERE order_id = 100;
Sample Program
This creates a users table, adds two users, then updates the email and city for user with id 1. Finally, it shows the updated row.
SQL
CREATE TABLE users (
  id INT PRIMARY KEY,
  name VARCHAR(50),
  email VARCHAR(50),
  city VARCHAR(50)
);

INSERT INTO users (id, name, email, city) VALUES
(1, 'John Doe', 'john@example.com', 'New York'),
(2, 'Jane Roe', 'jane@example.com', 'Los Angeles');

UPDATE users
SET email = 'john.doe@example.com', city = 'Boston'
WHERE id = 1;

SELECT * FROM users WHERE id = 1;
OutputSuccess
Important Notes
Always double-check your WHERE clause to avoid updating all rows by mistake.
You can update as many columns as you want in one statement.
If you omit the WHERE clause, every row in the table will be updated.
Summary
UPDATE changes data in existing rows.
Use SET to list columns and their new values, separated by commas.
WHERE controls which rows get updated; be careful with it.