SQL UPDATE Statement βοΈΒΆ
Prerequisites: SELECT Statement
Mentor's Note: People change. Prices change. Phone numbers change. The
UPDATEstatement is how your database keeps up with the real world. But be careful: forgetting aWHEREclause is the fastest way to get fired! β οΈ
π The Scenario: The Birthday Party πΒΆ
Imagine you have a list of friends. - The Update: Your friend "Rahul" just turned 21. - The Precise Action: You find Rahul's name and change his age to 21. β - The Disaster: You forget to look for Rahul and just shout "EVERYONE IS 21!" Now your list is ruined. β
π¨ Visual Logic: Targeted ModificationΒΆ
graph LR
A[(Table)] -- "WHERE id = 5" --> B[Target Row]
B -- "SET price = 100" --> C[Updated Row]
π» 1. The Basic SyntaxΒΆ
Example: Update a specific recordΒΆ
-- Scenario: Update phone number for Student 101
UPDATE students
SET phone = '9876543210'
WHERE roll_no = 101;
π» 2. Updating Multiple Columns πΒΆ
You can change several fields at once by separating them with commas.
-- Scenario: Student moved house and changed email
UPDATE students
SET
city = 'Surat',
email = '[email protected]'
WHERE roll_no = 105;
π» 3. Updating with Logic (Expressions) βοΈΒΆ
You can use the existing value to calculate the new one.
-- Scenario: Give everyone in 'Sales' a 5% raise
UPDATE employees
SET salary = salary * 1.05
WHERE department = 'Sales';
β οΈ The "No-Where" Danger ZoneΒΆ
If you omit the WHERE clause, EVERY SINGLE ROW in the table will be updated.
-- π£ DO NOT DO THIS (unless you mean it)
UPDATE students SET status = 'Expelled';
-- Result: Congratulations, you have no students left!
π‘ Pro Tip: The "Safety First" WorkflowΒΆ
"Before running an
UPDATE, run aSELECTwith the exact sameWHEREclause. If theSELECTshows the correct 5 people, then copy thatWHEREclause into yourUPDATEstatement!"