Pcornel
Browse topics
Options
Recent
Favorites
Databases · Technical reference

INSERT, UPDATE and DELETE Safely

Direct answer

Safe data changes: preview with SELECT, run inside a transaction, check affected rows, keep a backup or undo path, and batch large changes.

When to use this

Use it before any UPDATE or DELETE on production data.

First 30 seconds

1. SELECT count(*) FROM t WHERE <cond>;.

2. BEGIN; then the UPDATE/DELETE.

3. Rows affected matches?

4. COMMIT; (or ROLLBACK;).

5. Backup/undo plan exists.

Operational verification

preview → transaction → change → verify → commit

Context & applicabilityCommon mistakes · platform/version boundaries
Platform / version applicability
MariaDB / MySQL / PostgreSQL / Microsoft SQL Server concepts
applies
Structured applicability is explicit Topic metadata; it does not infer compatibility beyond the stored rows.
At a glance

Operational reference

Fast context before you go deeper.

PlatformMariaDB / MySQL / PostgreSQL / Microsoft SQL Server concepts
Scope / prerequisiteUse it before any UPDATE or DELETE on production data.
What next?2 suggested next steps
Evidence0
On this pageJump to a specific section
Operational workflow

Verification & Troubleshooting

Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.

2 steps Observe → verify → isolate → change minimally → repeat the original test.
ObservedRecord what the original test actually shows

Capture the concrete output, symptom, packet, log or counter before changing anything.

Step 1 How to verify Verify boundary

Confirm the affected count matches. Check replication lag after large changes. Verify application behaviour on the changed rows.

Step 2 Common failures Narrow the fault

An UPDATE without WHERE changes every row. Long transactions block other writers and vacuum. Cascading foreign keys can delete far more rows than the statement suggests.

Key points

No WHERE = every row. Large deletes lock and bloat — batch them. Some clients auto-commit; disable or wrap in BEGIN.

Key checks
  • SELECT count(*) FROM t WHERE <cond>; — first check for this topic
  • psql -c "SELECT now(), version();" — PostgreSQL reachable and version
  • mysql -e "SELECT NOW(), VERSION();" — MariaDB/MySQL reachable and version
  • sqlcmd -S <server> -Q "SELECT @@VERSION" — SQL Server reachable and version
ReferenceWhat it is1 section · depth on demand

How it works

Each changed row takes a lock until the transaction ends. Large updates create many row versions or undo records and can lag replicas. Batching (for example 1,000 rows at a time) keeps locks and replication delay small.

ReferenceImportant terms & boundaries2 sections · depth on demand

In depth

A safe change procedure

1. Write the WHERE clause as a SELECT first and check the count and a sample.

2. Run the change inside a transaction and compare the reported row count.

3. Check with a SELECT, then COMMIT — or ROLLBACK if anything differs.

BEGIN;
SELECT count(*) FROM orders WHERE status = 'test';           -- 1 248
UPDATE orders SET status = 'archived' WHERE status = 'test' RETURNING id;  -- UPDATE 1248
COMMIT;

In the mysql client, --safe-updates (SET sql_safe_updates = 1) refuses UPDATE/DELETE without a key in WHERE or a LIMIT.

Large changes in batches

One huge statement holds locks for its whole duration, creates a large undo/WAL volume and makes replicas lag. Batch by key range instead:

-- repeat until 0 rows
DELETE FROM events WHERE id IN (
  SELECT id FROM events WHERE created_at < now() - interval '1 year' ORDER BY id LIMIT 10000);

Pause between batches if replication lag grows.

Upsert instead of check-then-insert

INSERT INTO stock (sku, qty) VALUES ('A1', 5)
ON CONFLICT (sku) DO UPDATE SET qty = stock.qty + EXCLUDED.qty;        -- PostgreSQL
INSERT INTO stock (sku, qty) VALUES ('A1', 5) AS new
ON DUPLICATE KEY UPDATE qty = stock.qty + new.qty;                     -- MySQL 8.0.19+

A SELECT followed by INSERT from two sessions at once can both see "no row" and insert twice; the single statement relies on the unique constraint instead.

Source basisSource attribution states what this section is based on; it is not independent proof that the current environment matches it.

Common mistakes

  • UPDATE/DELETE without WHERE; no transaction for checks.
ReferenceConfiguration & state1 section · depth on demand

Safe pattern

BEGIN;
SELECT count(*) FROM orders WHERE status = 'test' AND created_at < '2026-01-01';
DELETE FROM orders WHERE status = 'test' AND created_at < '2026-01-01';
-- check affected rows matches the count
COMMIT;   -- or ROLLBACK;

Use --safe-updates in the MySQL client (blocks UPDATE/DELETE without a key in WHERE), delete large volumes in batches to avoid long locks and huge logs, and have a tested backup before bulk changes.

Additional reference context Scope · expected state · examples · history · terminology Open only when you need the supporting context
Terminology layer

Terms & aliases

Hover a linked term for a quick definition; click it to open its glossary entry. Aliases are other names that find this Topic in search.

Aliases that resolve here
insert, update and delete safelysafe sql update deletetransaction rollback
Confirmation

Confirm action

Continue?