BEGIN / COMMIT / ROLLBACK: Start a transaction, then make all its changes permanent (COMMIT) or throw them all away (ROLLBACK). BEGIN, COMMIT and ROLLBACK control a database transaction. BEGIN starts it. All changes after that are provisional. COMMIT makes them permanent, and ROLLBACK throws them all away. This is useful in two ways. In application code, it keeps related changes together, so a crash or error cannot leave half an order in the database. In a manual session, it gives you a safety net: run a risky DELETE inside a transaction, check how many rows it affected, and roll back if the number is wrong.
Frequently asked questions about BEGIN / COMMIT / ROLLBACK
What should you keep in mind with BEGIN / COMMIT / ROLLBACK?
Some statements, such as schema changes in MySQL, commit automatically and cannot be rolled back. Check how your database handles them before relying on a transaction. And do not leave a transaction open in a console while you go for coffee; it can block other queries.
What does an example of BEGIN / COMMIT / ROLLBACK look like?
BEGIN; DELETE FROM logs WHERE created_at < now() - interval '90 days'; ROLLBACK; -- changed my mind
Use when code runs things at the same time - threads, async/await, queues and workers, parallel requests, cron jobs, webhooks that retry - or when a bug only happens "sometimes" or under load. Covers race conditions, deadlocks, mutexes/locks, atomic operations, idempotency, message queues and backpressure, with Laravel and database examples.
Master SQL query optimization, indexing strategies, and EXPLAIN analysis to dramatically improve database performance and eliminate slow queries. Use when debugging slow queries, designing database schemas, or optimizing application performance.