Learn SQL
-- performance.batching_transactions

Batching & Transactions in SQL

Fewer round-trips, grouped writes, all-or-nothing units

--concept

Two workhorses of real-world performance. Batching: one INSERT of 500 rows beats 500 single INSERTs, because the engine parses and commits once instead of per row. Transactions: wrapping related writes in BEGIN … COMMIT makes them one all-or-nothing unit — either every change lands or none does, and readers never see the half-done middle.

--how it works
1

One statement, many rows

INSERT INTO t (…) VALUES (…), (…), (…) — a single parse, plan and commit for hundreds of rows instead of one round-trip each.

2

Group writes into transactions

BEGIN; … COMMIT; makes a set of statements one unit of work — all visible together, or not at all.

3

Commit once, fsync once

The durability flush (the expensive part) happens per COMMIT — a thousand writes in one transaction share a single flush.

4

ROLLBACK as the safety net

If statement 3 of 4 fails, ROLLBACK returns the database to the pre-BEGIN state — no half-done work is ever visible.

5

Keep them short

Long transactions hold locks and bloat the log. Batch the rows inside the transaction; never wrap hours of user think-time in one.

--visualization
BEGIN;1 · UPDATEUPDATE employees SET salary = salary * 1.05 WHERE department = 'Engineering'3 rows ✓2 · INSERTINSERT INTO audit (action, done_at) VALUES ('raise_engineering', NOW())…other sessions see the old data until COMMITAlice · Engineering85,000Bob · Sales52,000Cynthia · Engineering91,000David · Marketing47,000Elena · Sales58,000Farid · Engineering73,000
changed inside the transaction committed ✓ rolled back ✗
Stage 1 / 4
BEGIN opens a transaction: the raise and its audit row will be one all-or-nothing unit.
--example
query.sql
1BEGIN;
2UPDATE employees SET salary = salary * 1.05 WHERE department = 'Engineering';
3INSERT INTO audit (action, done_at) VALUES ('raise_engineering', NOW());
4COMMIT;
Result
result
3 rows updated, 1 row inserted — transaction committed

The raise and its audit row are one unit: if the INSERT fails, ROLLBACK removes the raise too — an audit log that never lies. Committing once also means one durability flush instead of two, and other sessions see either “no raise, no audit row” or both, never a half-finished state.

--variants

Multi-row INSERT

The simplest batching win.

query.sql
1INSERT INTO employees (id, name, department, salary, age) VALUES
2 (8, 'Hana', 'Sales', 54000, 28),
3 (9, 'Ivan', 'Engineering', 77000, 36),
4 (10, 'Jules', 'Marketing', 51000, 25);
Result
result
3 rows inserted in one statement — one parse, one plan, one commit
1Three rows, one round-trip: network latency and parse overhead are paid once, not thrice.
2On a WAN the difference is dramatic — 1,000 single inserts at 1 ms latency is ≥ 1 second of pure waiting.
3Chunk very large sets (10k–50k rows per statement) to stay under packet and memory limits.

All-or-nothing business operation

The raise and its audit row live or die together.

query.sql
1BEGIN;
2UPDATE employees SET salary = salary * 1.05 WHERE department = 'Engineering';
3INSERT INTO audit (action, done_at) VALUES ('raise_engineering', NOW());
4COMMIT;
Result
result
3 rows updated, 1 row inserted — transaction committed
1If the INSERT fails (bad column, permissions), the UPDATE rolls back too — no unaudited raises.
2Other sessions see either the pre-BEGIN world or the post-COMMIT one, never the middle.
3This atomicity is the “A” in ACID and the reason two related writes belong in one transaction.

ROLLBACK — the undo button

Mistakes inside a transaction vanish.

query.sql
1BEGIN;
2DELETE FROM employees;
3-- forgot the WHERE. panic? no —
4ROLLBACK;
5SELECT COUNT(*) FROM employees;
Result
count
6
1The DELETE erased rows only for this session; COMMIT never ran.
2ROLLBACK restores the pre-BEGIN state — count is back to 6.
3The habit that saves careers: BEGIN before risky data changes, verify, then COMMIT.

What others see mid-transaction

Isolation keeps half-done work invisible.

query.sql
1BEGIN;
2UPDATE employees SET salary = 56000 WHERE id = 2;
3-- second session: SELECT salary FROM employees WHERE id = 2;
4-- → 52000 (last committed)
5COMMIT;
6-- second session now reads 56000
Result
observerseen value
before commit: 52000after commit: 56000
1Uncommitted changes are private to the transaction (MVCC or locking, engine-dependent).
2No torn state leaks: readers never see Bob’s salary change twice or half-apply.
3Isolation level tunes this: READ COMMITTED vs REPEATABLE READ vs SERIALIZABLE.
--key facts
ACIDAtomicity, Consistency, Isolation, Durability — the guarantees a transaction bundles
Batch sizethousands of rows per INSERT is fine; millions in one statement exhaust memory — chunk them
Isolation levelsREAD COMMITTED, REPEATABLE READ, SERIALIZABLE trade concurrency strictness for speed
--use cases
ETL loads: chunked multi-row INSERTs inside bounded transactions
Money and inventory: transfer-out + transfer-in in one transaction, always
Audit trails: the change and its audit row commit together
API endpoints: one request → one transaction, rolled back on any error
--under the hood
Single-statement autocommit still costs a round-trip and a log flush each — the batching rules apply even without explicit BEGIN.
Group commit / synchronous_commit tuning lets high-throughput writers share flushes — read your engine’s docs before assuming fsync is the bottleneck.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Take the queries you just visualized and see the data structures that power real databases.