Working with Data Lesson 6 of 13
MySQL CRUD — INSERT, SELECT, UPDATE and DELETE
Create, read, update and delete rows in MySQL, insert many rows at once, use INSERT ... ON DUPLICATE KEY UPDATE, and protect your data with safe-update habits.
Almost every app does four things with data: Create, Read, Update and Delete, together called CRUD. You learned the SQL for each in the SQL course; this lesson adds MySQL-specific tips. Try the live examples on the store database.
Create: INSERT
INSERT INTO products (name, category, price, stock)
VALUES ('Vinegar', 'Cooking', 16, 25),
('Asukal (1 kg)', 'Cooking', 75, 30);
SELECT id, name, price FROM products WHERE category = 'Cooking';
One INSERT with several rows is much faster than many separate inserts.
Insert or update: ON DUPLICATE KEY UPDATE
MySQL can insert a row, or update it if a row with the same primary or unique key already exists:
INSERT INTO inventory (barcode, name, stock)
VALUES ('4800016644290', 'Kape 3-in-1', 50)
ON DUPLICATE KEY UPDATE stock = stock + VALUES(stock);
The first time, the product is added with 50 in stock. The next time the same barcode is delivered, 50 more is added. (Newer MySQL versions prefer an alias syntax: ... AS new ON DUPLICATE KEY UPDATE stock = stock + new.stock.)
Read: SELECT
SELECT name, price, stock, price * stock AS stock_value
FROM products
ORDER BY stock_value DESC
LIMIT 5;
Update
UPDATE products
SET price = price + 2
WHERE category = 'Drinks';
SELECT name, price FROM products WHERE category = 'Drinks';
Delete
DELETE FROM products WHERE stock = 0;
SELECT COUNT(*) AS remaining FROM products;
Safe updates mode
MySQL has a safety switch that blocks UPDATE and DELETE statements without a WHERE that uses a key, preventing "oops, I changed every row" disasters. MySQL Workbench turns it on by default:
SET SQL_SAFE_UPDATES = 1;
DELETE FROM products; -- refused: no WHERE on a key column
Error
ERROR 1175 (HY000): You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column.
Soft delete example
ALTER TABLE products ADD COLUMN deleted_at DATETIME NULL;
-- "Delete"
UPDATE products SET deleted_at = NOW() WHERE id = 15;
-- Show only active products
SELECT * FROM products WHERE deleted_at IS NULL;
-- Undo
UPDATE products SET deleted_at = NULL WHERE id = 15;
Affected rows
After an INSERT, UPDATE or DELETE, MySQL reports how many rows changed:
Output
Query OK, 3 rows affected (0.004 sec) Rows matched: 3 Changed: 3 Warnings: 0
In PHP, the same number comes from $stmt->rowCount(). Checking it tells your app whether an update actually found the row.
Quick Quiz
Check what you learned. Walang grade ito, practice lang. 🙂
By Sir Reyel · Last updated 2026-12-04