Interview Q&A · SQL · 10 questions in this topic
UPDATE, DELETE & Safe Writes — SQL Interview Q&A
Changing data without disasters — guarded writes, transactions, upserts and bulk patterns. Part of Modifying Data · 192 questions in the SQL bank.
How do UPDATE and DELETE work?
Answer
UPDATE SET assigns new values to matching rows; DELETE removes matching rows. Both take WHERE — without it, every row changes. Both run inside transactions, so wrapping in BEGIN ... COMMIT/ROLLBACK makes them reviewable and reversible.
The safety ritual: SELECT the WHERE first, then convert to UPDATE/DELETE.
Example
-- look before you leap: SELECT * FROM employees WHERE id = 99; UPDATE employees SET salary = 95000 WHERE id = 99; DELETE FROM employees WHERE id = 99;
💡 SELECT-first is the safety habit interviewers want to hear, not just the syntax.
How do you update safely in production (guarded writes)?
Answer
Preview with SELECT COUNT(*) on the same WHERE, run inside an explicit transaction, verify ROW_COUNT, then COMMIT — with a ROLLBACK path rehearsed. LIMIT on UPDATE/DELETE (MySQL) adds a blast-radius cap; staging the change on a copy first proves the predicate.
No WHERE, no run: the best UPDATE is the one you previewed.
Key points
- 1Preview — SELECT the predicate, check the count.
- 2Transact — BEGIN, verify, then COMMIT.
- 3Cap — LIMIT guards where supported.
Example
BEGIN; UPDATE employees SET salary = salary * 1.1 WHERE department = 'Sales'; -- check row count, spot-check rows... COMMIT; -- or ROLLBACK
How do you update from another table (UPDATE ... JOIN / FROM)?
Answer
PostgreSQL/SQLite use UPDATE ... FROM (join the source in FROM, correlate in WHERE); MySQL/SQL Server use UPDATE ... JOIN. Both must correlate exactly — a missing join condition cross-updates every row.
Correlated-subquery form (SET col = (SELECT ...)) is the portable fallback where JOIN-update is unsupported.
Example
-- PostgreSQL form: UPDATE employees e SET salary = b.new_pay FROM pay_bands b WHERE e.band = b.band;
What is an upsert (INSERT ... ON CONFLICT / ON DUPLICATE KEY)?
Answer
Upsert inserts or, on key conflict, updates instead — one atomic statement replacing error-prone select-then-insert races. PostgreSQL/SQLite: ON CONFLICT (key) DO UPDATE. MySQL: ON DUPLICATE KEY UPDATE.
It needs a real uniqueness constraint to conflict on — without one, duplicates slip through silently.
Example
-- PostgreSQL / SQLite: INSERT INTO counters (k, n) VALUES ('hits', 1) ON CONFLICT (k) DO UPDATE SET n = counters.n + 1;
💡 Atomicity plus the required unique constraint is the complete upsert answer.
How do you delete safely (soft vs hard deletes)?
Answer
Hard DELETE removes rows physically (with WHERE, in a transaction). Soft delete flags rows (deleted_at timestamp) — recoverable, auditable, but every query must filter, and unique constraints need partial indexes to ignore dead rows.
Default to soft deletes for user/business data (recovery, compliance); hard deletes for ephemeral/staging data and GDPR erasure.
Example
-- soft delete: UPDATE users SET deleted_at = now() WHERE id = 7; SELECT * FROM users WHERE deleted_at IS NULL;
💡 Recoverability vs query-tax is the trade-off to state.
How do you bulk-insert efficiently?
Answer
Single multi-row INSERT (thousands per statement), COPY (PostgreSQL) / LOAD DATA (MySQL) for files, prepared-statement batches in one transaction, with indexes/constraints deferred where safe. Row-by-row autocommitted INSERTs are the slow path — transaction and network overhead per row.
Order of magnitude: single transaction plus bulk protocol beats per-row commits 10-100x.
Key points
- 1Batch — multi-row VALUES, COPY/LOAD DATA.
- 2Transact — one transaction, not per-row commits.
- 3Defer — drop/rebuild indexes around giant loads.
Example
-- PostgreSQL bulk: COPY employees FROM '/data/emp.csv' WITH (FORMAT csv, HEADER);
What is the difference between `DELETE`, `TRUNCATE` and `DROP`?
Answer
DELETE removes selected rows transactionally (logged, rollback-able, triggers fire). TRUNCATE empties fast via page deallocation (resets sequences, minimal logging, restricted rollback in some engines). DROP removes the table definition itself.
Recovery story decides: need undo, use DELETE; need speed on staging, TRUNCATE; removing structure, DROP.
Key points
- 1DELETE — selective, logged, transactional.
- 2TRUNCATE — full, fast, sequence-resetting.
- 3DROP — structure gone.
How do you update millions of rows without locking the table?
Answer
Batch in small keyset chunks (WHERE id BETWEEN ... LIMIT n per transaction) with pauses — each chunk commits fast, replication stays close, locks stay short. Single giant UPDATE holds locks, bloats WAL/undo, and blocks everything.
Chunk by indexed key order, track progress, make it resumable and idempotent.
Example
-- batched pattern (repeat with advancing bounds): UPDATE employees SET band = 'x' WHERE id BETWEEN 1 AND 10000;
💡 Small chunks plus resumability is the production-update doctrine.
How do you prevent lost updates (two writers, one row)?
Answer
Optimistic locking (version column checked in WHERE — update fails if changed), SELECT ... FOR UPDATE (pessimistic row lock in a transaction), or atomic single-statement updates (SET n = n + 1). Read-modify-write across statements without protection loses silently.
Atomic statements for counters; version columns for business entities; locks for multi-row invariants.
Example
-- optimistic: fails safely if version moved UPDATE accounts SET balance = 90, version = 6 WHERE id = 1 AND version = 5;
What does RETURNING do (PostgreSQL/SQLite)?
Answer
RETURNING returns affected rows from INSERT/UPDATE/DELETE in the same statement — no second SELECT, no race between write and read. Fetch new ids, updated values, or deleted snapshots atomically.
It collapses write-then-read round trips and the race windows they open.
Example
UPDATE employees SET salary = 95000 WHERE id = 99 RETURNING id, name, salary;
💡 Atomic write-plus-read is the RETURNING pitch; new-id fetching is its killer use.
Learn this topic
Recommended resourcesAffiliate links · may earn us a commission