โ๏ธ Lesson 7: Modifying Data (INSERT, UPDATE, DELETE)
โฑ๏ธ Estimated time: 20 minutes | Difficulty: Intermediate
Handle with Care
These commands directly modify the data in your database. Always double-check your
conditions (especially for UPDATE and DELETE) to avoid accidental data loss!
INSERT โ Add New Data
-- Insert one row
INSERT INTO users (name, email, age)
VALUES ('Alice', 'alice@email.com', 25);
-- Insert multiple rows
INSERT INTO users (name, email, age) VALUES
('Bob', 'bob@email.com', 30),
('Charlie', 'charlie@mail.io', 22),
('Diana', 'diana@test.com', 28);
UPDATE โ Modify Existing Data
-- Update specific row
UPDATE users SET age = 26 WHERE name = 'Alice';
-- Update multiple columns
UPDATE users SET email = 'new@email.com', age = 31
WHERE id = 2;
-- โ ๏ธ Without WHERE, updates ALL rows!
UPDATE users SET age = 0; -- DANGER! Changes everyone!
DELETE โ Remove Data
-- Delete specific row
DELETE FROM users WHERE id = 3;
-- Delete with condition
DELETE FROM users WHERE age < 18;
-- โ ๏ธ Without WHERE, deletes ALL rows!
DELETE FROM users; -- DANGER! Removes everything!
-- TRUNCATE: faster way to delete all rows
TRUNCATE TABLE users;
โ ๏ธ Safety Tips
- ๐ Always use WHERE with UPDATE and DELETE
- ๐งช Test with SELECT first:
SELECT * FROM users WHERE id = 3; - ๐พ Backup before bulk operations
- ๐ Use transactions for safe changes