Reading data with SELECT is safe to practise. Changing data deserves more care, because a single missing condition can rewrite or remove every row in a table. The three statements that change data are INSERT for adding rows, UPDATE for modifying rows, and DELETE for removing rows. This guide covers sql insert update delete with an emphasis on safety: preview first, filter precisely, wrap risky work in transactions, and confirm the affected row count before you move on.
The examples use a products table with id, product_name, category, price, stock, and created_at, and a customers table with id, first_name, email, and status. The habits matter more than the table names. A developer who always previews an UPDATE with the same WHERE clause as a SELECT will avoid nearly every horror story in this area. To find the rows you plan to change, the filtering patterns in our sql select query examples are the exact ones to reuse.
Adding Rows With INSERT
INSERT names the table, lists the target columns, and provides values in the same order. Always list columns explicitly rather than relying on table order, because a later schema change would otherwise shuffle your values into the wrong columns. Text goes in single quotes, numbers stay bare, and NULL inserts a missing value where the column allows it.
INSERT INTO products (product_name, category, price, stock)
VALUES ('Wireless Mouse', 'Accessories', 24.99, 150);
INSERT INTO customers (first_name, email, status)
VALUES ('Amina', 'amina@example.com', 'active'),
('Jonas', 'jonas@example.com', 'active'),
('Priya', 'priya@example.com', 'pending');
The first statement adds one product; the id and created_at columns are omitted, so the database fills them from an auto-increment rule and a default timestamp if the table defines them. The second statement adds three customers in one go by listing several value groups separated by commas, which is faster and cleaner than three separate statements. If any row in a multi-row insert fails a constraint, most databases reject the whole statement, leaving the table unchanged. That all-or-nothing behaviour at statement level is helpful, but it is not a substitute for the explicit transactions covered later.
You can also insert the result of a query, which is the standard way to copy or archive data. The SELECT must return columns matching the listed target columns in number and compatible type. This pattern powers everything from seeding a summary table to moving old orders into an archive.
INSERT INTO archived_orders (id, customer_id, total_price, order_date) SELECT id, customer_id, total_price, order_date FROM orders WHERE order_date < '2025-01-01';
Here every order dated before 2025 is copied into archived_orders. Notice there is no VALUES keyword, because the SELECT supplies the rows. Test the SELECT alone first and check its count; only then place it under the INSERT. Archiving this way copies data but does not remove the originals, so a follow-up DELETE on the source is a separate, deliberate step. Summaries that feed tables like this often come from the aggregations in sql group by having.
Changing Rows With UPDATE
UPDATE names the table, sets new values with SET, and restricts the damage with WHERE. The WHERE clause is technically optional, and that is precisely the danger: without it, the update applies to every row. Treat a missing WHERE on UPDATE as an error unless you can say out loud why the whole table should change, such as resetting a cache counter.
UPDATE products SET price = 21.99, stock = 140 WHERE id = 12; UPDATE customers SET status = 'inactive' WHERE last_login_at < '2025-01-01' AND status = 'active';
The first statement changes price and stock for exactly one product, targeted by its primary key, the safest kind of update. The second marks long-dormant accounts inactive, and its WHERE carries two conditions so recently active or already inactive accounts are untouched. New values can be computed from old ones, which is handy for price rises and stock adjustments without reading the value into application code first.
UPDATE products SET price = price * 1.05 WHERE category = 'Accessories'; UPDATE products SET stock = stock - 1 WHERE id = 12 AND stock > 0;
The first raises accessory prices by five percent by multiplying each current price by 1.05. The second decrements stock by one after a sale, and the stock greater than zero guard prevents the count going negative even if two sales race each other. Guards inside WHERE are a quiet superpower: the update simply affects zero rows when the guard fails, and your code can check the affected count to decide what happened.
Removing Rows With DELETE
DELETE removes whole rows matching its WHERE clause. Like UPDATE, it becomes a table-wide operation when WHERE is missing, so the same preview discipline applies. Deleting is permanent in normal operation; there is no recycle bin unless your application builds one with a status flag or an archive table.
DELETE FROM customers WHERE id = 342; DELETE FROM sessions WHERE expires_at < NOW(); DELETE FROM orders WHERE status = 'cancelled' AND order_date < '2024-01-01';
The first removes one customer by key. The second clears expired login sessions, a routine cleanup where NOW() supplies the current time in MySQL and compatible systems; other databases spell the current timestamp differently, but the pattern is the same. The third purges old cancelled orders under two conditions, limiting the blast radius to records that are both unwanted and old. Before any bulk delete, run a SELECT COUNT(*) with the identical WHERE, note the number, and compare it with the deleted count the database reports afterwards. If the numbers differ from your expectation, stop and investigate rather than continuing a cleanup script.
Deleting every row has two spellings. DELETE FROM table removes rows one by one, can be filtered, and can be rolled back inside a transaction, but is slower on huge tables. TRUNCATE TABLE empties the table quickly and usually resets auto-increment counters, but cannot take a WHERE clause and has stricter permission and rollback behaviour that varies by database. Choose DELETE for controlled work and reserve TRUNCATE for disposable tables such as test fixtures. To empty related tables in the right order when foreign keys exist, delete child rows before parent rows, or temporarily follow the relationship checks described alongside sql joins explained.
Transactions: All or Nothing
A transaction groups several statements into one unit that either fully succeeds or fully rolls back. Transferring money, placing an order with stock changes, and archiving then deleting are all transaction-shaped jobs, because a half-finished state is worse than no change at all. BEGIN starts the unit, COMMIT saves it, and ROLLBACK undoes everything since BEGIN. In PostgreSQL the starter keyword can also be BEGIN TRANSACTION, and SQL Server uses BEGIN TRANSACTION with COMMIT TRANSACTION; the concept is identical.
BEGIN; UPDATE accounts SET balance = balance - 100 WHERE id = 1; UPDATE accounts SET balance = balance + 100 WHERE id = 2; COMMIT;
This moves 100 units between two accounts. If the second update failed after the first succeeded, issuing ROLLBACK instead of COMMIT would restore both balances, so money never vanishes mid-transfer. Inside an open transaction, run a SELECT to inspect the changed rows before committing; you see your own uncommitted changes, while other sessions usually still see the old data. Build the habit of deciding the commit only after that inspection. If your tool has an autocommit setting, know whether each statement commits immediately, because a transaction you assumed was open may not be.
RETURNING, Affected Rows and Upserts
Several databases can hand back the rows a change just touched. PostgreSQL and SQLite support a RETURNING clause on INSERT, UPDATE, and DELETE, which saves a follow-up SELECT when you need a generated id or the final stored values. MySQL does not offer RETURNING in the same way, so code there typically reads LAST_INSERT_ID() after an insert or selects the row by key.
INSERT INTO products (product_name, category, price, stock)
VALUES ('USB-C Cable', 'Accessories', 9.99, 300)
RETURNING id, created_at;
UPDATE products
SET stock = stock + 50
WHERE id = 12
RETURNING product_name, stock;
The first statement returns the new product id and creation timestamp in the same round trip. The second confirms the restocked level immediately. Where RETURNING is unavailable, always check the affected-row count your driver reports: an update that should touch one row but reports 4,000 is a stop-the-line event, usually meaning a WHERE clause was dropped or mistyped.
An upsert inserts a row, or updates it when a unique key already exists. It suits settings tables, counters, and imports that may repeat. MySQL spells it with ON DUPLICATE KEY UPDATE, while PostgreSQL uses ON CONFLICT. The idea is shared even though the syntax is not.
-- MySQL
INSERT INTO settings (setting_key, setting_value)
VALUES ('theme', 'dark')
ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value);
-- PostgreSQL
INSERT INTO settings (setting_key, setting_value)
VALUES ('theme', 'dark')
ON CONFLICT (setting_key)
DO UPDATE SET setting_value = EXCLUDED.setting_value;
In both versions, the first run inserts the theme setting and later runs update it in place, because setting_key is unique. Upserts remove the clumsy check-then-write pattern and the race condition hiding inside it. Only use them where a genuine unique constraint exists; without one, the conflict handling never triggers and duplicates quietly pile up.
A Safe Change Checklist
Professional data changes follow a short ritual. First, write the WHERE clause as a SELECT and read the exact rows. Second, check the count and ask whether that number makes business sense. Third, start a transaction when the tool and database allow it. Fourth, run the change and compare the affected count with the preview count. Fifth, select the changed rows once more, then commit. Sixth, for bulk jobs on live systems, keep a backup or an undo query ready; for an UPDATE, that can mean selecting the original values into a holding table first, and for a DELETE, archiving before removing.
Also mind two quieter risks. One is updating by a non-unique column, such as setting a password by first name alone, which can hit several people. Target primary keys or verified unique columns wherever possible. The other is running maintenance during peak traffic on very large tables, where a long update can lock rows and stall the application; schedule big changes, batch them in modest chunks with a LIMIT where your database supports it for UPDATE and DELETE, and monitor as you go. Routine oversight queries for spotting locks and large tables live in our mysql common queries roundup, which pairs well with this checklist.
Conclusion
INSERT adds, UPDATE modifies, and DELETE removes, and all three are safe when you preview with SELECT, filter by precise keys, guard computed changes, and wrap multi-step work in transactions. Count rows before and after, use RETURNING or affected counts as confirmation, and keep an undo path for bulk jobs. Care at this stage is cheap; recovering from an unfiltered update is not.
Tagged: data safety sql delete sql examples sql insert sql update transactions


