Developer Guides, Cheat Sheets & Tools
SQL course - Part 9: TRANSACTIONS AND INTEGRITY
| Part index | Prerequisites | Previous | Next | Full course |
π PART 9 β TRANSACTIONS AND INTEGRITY
42. Transactions and ACID
| ποΈ Level | β±οΈ Time | π― After this chapter you canβ¦ |
|---|---|---|
| π’π‘ BeginnerβIntermediate | 30 min | Group changes into all-or-nothing units Β· Use savepoints Β· Explain ACID in plain words Β· Know which statements cannot be undone |
[!NOTE] π In plain words: A transaction is a group of changes that all succeed together or all fail together. There is no halfway.
π Analogy: A bank transfer. Money leaves account A and arrives in account B. If the power fails between those two steps, you must not end up in a world where the money left A but never reached B. A transaction guarantees that world cannot exist.
42.1 πΈ The classic example
-- β
Works in BOTH: a two-account table to try this on
CREATE TABLE accounts (
account_id INT PRIMARY KEY,
balance DECIMAL(12,2) NOT NULL
);
INSERT INTO accounts (account_id, balance) VALUES (1, 1000.00), (2, 250.00);
-- π₯ MSSQL
BEGIN TRANSACTION;
UPDATE accounts SET balance = balance - 500 WHERE account_id = 1;
UPDATE accounts SET balance = balance + 500 WHERE account_id = 2;
COMMIT; -- both changes become permanent
-- ROLLBACK; -- OR both changes are undone
-- π¦ MySQL: identical, except the transaction starts with START TRANSACTION
START TRANSACTION;
UPDATE accounts SET balance = balance - 500 WHERE account_id = 1;
UPDATE accounts SET balance = balance + 500 WHERE account_id = 2;
COMMIT;
Without a transaction, a crash between those two statements destroys 500 units of money. With one, either both happen or neither does.
-- β
π₯ MSSQL β a real ShopDB transaction: place an order and take stock, all or nothing
BEGIN TRANSACTION;
INSERT INTO orders (customer_id, employee_id, order_date, status)
VALUES (1, 3, '2026-09-09', 'Paid');
INSERT INTO order_items (order_id, product_id, unit_price, quantity, discount)
VALUES (SCOPE_IDENTITY(), 5, 899.00, 1, 0); -- the order_id just generated
UPDATE products SET units_in_stock = units_in_stock - 1 WHERE product_id = 5;
COMMIT;
-- β
π¦ MySQL β the same transaction
START TRANSACTION;
INSERT INTO orders (customer_id, employee_id, order_date, status)
VALUES (1, 3, '2026-09-09', 'Paid');
INSERT INTO order_items (order_id, product_id, unit_price, quantity, discount)
VALUES (LAST_INSERT_ID(), 5, 899.00, 1, 0); -- the order_id just generated
UPDATE products SET units_in_stock = units_in_stock - 1 WHERE product_id = 5;
COMMIT;
[!NOTE] π Why this must be one transaction: if the stock update failed after the order was created, you would have sold an item you do not have. If the order insert succeeded but the item insert failed, you would have an empty order. Only all-or-nothing is correct.
42.2 ποΈ ACID β the four guarantees
| Letter | Property | Plain-English meaning | What breaks without it |
|---|---|---|---|
| A | Atomicity | All the steps happen, or none do | Money leaves one account and vanishes |
| C | Consistency | The data follows all your rules (constraints) before and after every change | Orders reference customers who do not exist |
| I | Isolation | Transactions running at the same time do not mess up each otherβs work | Two people buy the last item |
| D | Durability | Once committed, it survives a crash | A confirmed payment disappears after a reboot |
π Analogies:
- Atomicity β a light switch. On or off. Never βhalf on.β
- Consistency β chess rules. Every move leaves a legal board position.
- Isolation β restaurant tables. Diners at one table do not eat from another tableβs plates.
- Durability β writing in permanent ink. Once written, it stays written.
[!IMPORTANT] π― When do I actually need to write
BEGIN TRANSACTION? Every single statement is already atomic on its own, so you only need an explicit transaction when two or more statements must succeed or fail together:
Situation Transaction needed? One UPDATE, oneINSERT, oneDELETEβ No β already atomic Insert an order and its line items β Yes Move money / stock from one row to another β Yes Insert a parent then its children β Yes Any UPDATE/DELETEyou type by hand on a live (production) serverβ Yes β as an undo button A read-only SELECTβ No (unless several queries must see exactly the same data) A long report β No β and never inside a write transaction π Common mistake: wrapping a single
UPDATEin a transaction βto be safeβ in application code and then forgetting to commit. The locks stay held, other users pile up behind it, and the app appears frozen. One statement needs no transaction β the engine already gives you one.
42.3 βοΈ Transaction syntax
-- π₯ MSSQL
BEGIN TRANSACTION; -- or BEGIN TRAN
-- statements
COMMIT TRANSACTION; -- or COMMIT
-- or ROLLBACK TRANSACTION;
-- Named transactions and savepoints (a savepoint = a bookmark you can roll back to)
BEGIN TRANSACTION order_creation;
SAVE TRANSACTION before_items;
-- ...
ROLLBACK TRANSACTION before_items; -- undo back to the savepoint only
COMMIT TRANSACTION order_creation;
SELECT @@TRANCOUNT AS open_transactions; -- how deeply nested am I?
-- π¦ MySQL
START TRANSACTION; -- or BEGIN
-- statements
COMMIT;
-- or ROLLBACK;
-- Savepoints
START TRANSACTION;
INSERT INTO orders (customer_id, order_date) VALUES (1, CURDATE());
SAVEPOINT after_order;
INSERT INTO order_items (order_id, product_id, unit_price, quantity)
VALUES (LAST_INSERT_ID(), 999, 10.00, 1); -- fails: no product 999
ROLLBACK TO SAVEPOINT after_order; -- keep the order, drop the item
RELEASE SAVEPOINT after_order; -- optional: COMMIT releases it anyway
COMMIT;
42.4 π Autocommit β the default nobody notices
-- By default, BOTH engines run in autocommit mode (each statement is saved the moment it finishes):
UPDATE products SET unit_price = 1399 WHERE product_id = 1;
-- β‘ Already committed. No undo. This was its own transaction.
-- π¦ MySQL: turn autocommit off for a session
SET autocommit = 0;
UPDATE products SET unit_price = 1399 WHERE product_id = 1;
-- nothing is permanent yet
COMMIT; -- or ROLLBACK
SET autocommit = 1;
-- π₯ MSSQL: implicit transactions
SET IMPLICIT_TRANSACTIONS ON;
UPDATE products SET unit_price = 1399 WHERE product_id = 1;
COMMIT;
[!WARNING] β οΈ The habit that saves careers: on production, type
BEGIN TRANSACTIONbefore you type theUPDATEorDELETE. Run it, check the affected row count and a verificationSELECT, and only thenCOMMIT. It costs three seconds and buys you an undo button.
[!WARNING] β οΈ But do not leave a transaction open while you go to lunch. An uncommitted transaction holds locks. Other users wait behind it, the application runs out of free connections, and it appears to hang. Open, verify, commit β within seconds.
42.5 π₯ DDL and implicit commits
[!WARNING] β οΈ A crucial difference between the engines. DDL (Data Definition Language) means the statements that change structure:
CREATE,ALTER,DROP,TRUNCATE.
-- π¦ MySQL: DDL causes an IMPLICIT COMMIT. This cannot be rolled back:
START TRANSACTION;
INSERT INTO categories (category_name) VALUES ('Test');
CREATE TABLE oops (id INT); -- π₯ implicitly commits the INSERT above!
ROLLBACK; -- too late β 'Test' is permanent
-- π₯ MSSQL: DDL IS transactional. This works as you would hope:
BEGIN TRANSACTION;
CREATE TABLE oops (id INT);
INSERT INTO oops VALUES (1);
ROLLBACK; -- β
the table never existed
[!TIP] π‘ This is one of MSSQLβs genuinely nicer features β you can test a schema migration inside a transaction and roll it back if anything looks wrong. In MySQL you must be far more careful, because
CREATE,ALTER,DROP, andTRUNCATEall commit implicitly.
42.6 π How durability actually works
Both engines use write-ahead logging (WAL) β every change is written to a log file before the main data files are updated:
1. You COMMIT
2. The change is written to the TRANSACTION LOG on disk β durability point
3. The client is told "committed"
4. Later, a background process writes the data pages to the data files
If the server crashes between 3 and 4:
β on restart, the engine REPLAYS the log and reapplies your change.
β nothing is lost.
| Β | π₯ MSSQL | π¦ MySQL / InnoDB |
|---|---|---|
| Log name | Transaction log (.ldf) |
Redo log (ib_logfile) + binary log |
| Durability setting | Delayed durability (optional) | innodb_flush_log_at_trx_commit |
| Full durability | Default | = 1 (default) |
[!WARNING] β οΈ
innodb_flush_log_at_trx_commit = 2or0makes MySQL much faster and gives up the D in ACID. It is a legitimate choice for a cache or an analytics replica (a read-only copy of the database on another server); it is never acceptable for financial data. Know which one your server is set to.
42.7 π― Best practices
| β Do | β Do not |
|---|---|
| Keep transactions short | Hold one open across user interaction |
| Touch tables in a consistent order everywhere | Vary the order (this creates deadlocks) |
| Handle errors and roll back explicitly | Assume an error auto-rolls back (it often does not) |
| Read only what you need inside the transaction | Run a 10-minute report inside a write transaction |
| Set an appropriate isolation level | Use SERIALIZABLE βto be safeβ everywhere |
| Test the rollback path | Only test the happy path |
-- β
π₯ MSSQL β the safe pattern, worth memorizing
SET XACT_ABORT ON; -- any runtime error aborts and rolls back the transaction
BEGIN TRY
BEGIN TRANSACTION;
-- your work here
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;
THROW; -- re-raise so the caller knows it failed
END CATCH;
[!WARNING] β οΈ Without
SET XACT_ABORT ON, some MSSQL errors leave the transaction open and βdoomedβ β you cannot commit it, and if the client disconnects without rolling back, locks are held until the connection is cleaned up. Always turn it on in procedures that write data.
42.8 π§ͺ Try it yourself
- Start a transaction, delete all of
order_items, run aSELECT COUNT(*), then roll back and count again. - Use savepoints to insert an order, insert a bad item, roll back to the savepoint, and still commit the order.
- In MySQL, prove that a
CREATE TABLEinside a transaction commits your earlier insert. - Open a transaction in one session and try to read the changed row from a second session. What happens, and why?
π§ In practice β transactions and ACID
How to use it. Wrap related changes in
BEGIN TRANSACTIONβ¦COMMIT, withROLLBACKon failure. Atomicity means all or nothing; Consistency that constraints hold at the end; Isolation that concurrent transactions do not corrupt each other; Durability that a committed change survives a crash. Expected result: the database is never left in a half-finished state, whatever fails.When to use it. Whenever one logical operation touches more than one row or table β and that is the definition, not a rule of thumb.
Where to use it. Anything involving money, stock, or bookings. Scenario: placing an order inserts the order, inserts its items, and decrements stock. Without a transaction, a crash between steps two and three leaves an order for goods that were never reserved β and nobody discovers it until the warehouse cannot ship.
When not to use it. Do not hold a transaction open across user interaction, a network call, or an email send. Locks are held for the whole transaction, so a dialog box waiting for someone back from lunch can block the rest of the system. Do not wrap single statements in explicit transactions either β they are already atomic.
Best practices. Keep transactions short and entirely inside the database. Acquire locks in a consistent order across your application to reduce deadlocks. Make sure every code path commits or rolls back β an abandoned open transaction holds locks and grows the log until something fails. And be aware that an in-memory simulation never demonstrates atomicity: only a real engine, with a real rollback, proves the property.
43. Isolation levels, locking, and deadlocks
| ποΈ Level | β±οΈ Time | π― After this chapter you canβ¦ |
|---|---|---|
| π΄ Expert | 40 min | Name the four problems caused by users working at once Β· Pick an isolation level Β· Prevent and handle deadlocks Β· Find who is blocking whom |
[!NOTE] π In plain words: When many people use the database at once, their transactions can interfere. Isolation levels let you choose how much interference you will tolerate in exchange for how much speed.
π Analogy: Two people editing the same shared document. Either one waits until the other has finished (safe, but slow), or both type at once and hope they do not overwrite each other (fast, but risky). Isolation levels are the settings between those two extremes.
43.1 π» The four concurrency problems
β Dirty read β you read data another transaction has changed but not committed. If they roll back, you acted on data that never existed.
Session A: UPDATE products SET unit_price = 1 WHERE product_id = 5; (not committed)
Session B: SELECT unit_price FROM products WHERE product_id = 5; β reads 1 π±
Session A: ROLLBACK;
Session B now believes the price is 1. It never was.
β‘ Non-repeatable read β you read the same row twice in one transaction and get different values, because someone committed a change in between.
Session A: SELECT unit_price FROM products WHERE product_id = 5; β 899
Session B: UPDATE products SET unit_price = 799 WHERE product_id = 5; COMMIT;
Session A: SELECT unit_price FROM products WHERE product_id = 5; β 799 π±
β’ Phantom read β you run the same query twice and new rows have appeared.
Session A: SELECT COUNT(*) FROM orders WHERE status = 'Pending'; β 3
Session B: INSERT INTO orders (... status 'Pending' ...); COMMIT;
Session A: SELECT COUNT(*) FROM orders WHERE status = 'Pending'; β 4 π±
β£ Lost update β two transactions read the same value, both modify it, and the second overwrites the first.
Session A: reads stock = 10
Session B: reads stock = 10
Session A: sets stock = 10 - 3 = 7. COMMIT.
Session B: sets stock = 10 - 5 = 5. COMMIT.
8 units were sold; the table says 5 were taken. One update was lost. π±
43.2 ποΈ The four isolation levels
| Level | Dirty read | Non-repeatable read | Phantom read | Speed |
|---|---|---|---|---|
READ UNCOMMITTED |
β οΈ Possible | β οΈ Possible | β οΈ Possible | π Fastest |
READ COMMITTED |
β Prevented | β οΈ Possible | β οΈ Possible | β‘ Fast |
REPEATABLE READ |
β Prevented | β Prevented | β οΈ Possible* | π’ Slower |
SERIALIZABLE |
β Prevented | β Prevented | β Prevented | π Slowest |
* InnoDBβs REPEATABLE READ also prevents phantoms in most cases, thanks to *gap locking β it also locks the empty space between rows, so new rows cannot slip in.*
-- π₯ MSSQL
SET TRANSACTION ISOLATION LEVEL READ COMMITTED; -- stays in force for the rest of the session
BEGIN TRANSACTION;
-- ...
COMMIT;
-- π¦ MySQL
SET TRANSACTION ISOLATION LEVEL READ COMMITTED; -- applies to the NEXT transaction only
START TRANSACTION;
-- ...
COMMIT;
π The defaults differ, and it matters:
- MSSQL:
READ COMMITTEDusing locks β readers block writers and writers block readers.- MySQL/InnoDB:
REPEATABLE READusing MVCC (multi-version concurrency control: each reader sees a snapshot of the data, like a photo taken when it started) β readers never block writers, and writers never block readers.This is why the same application can behave very differently on the two engines. MSSQLβs
READ_COMMITTED_SNAPSHOTdatabase option switches it to MVCC behaviour and is one of the highest-value settings to enable on a busy OLTP system (lots of small, quick transactions β like an online shop):-- π₯ MSSQL ALTER DATABASE ShopDB SET READ_COMMITTED_SNAPSHOT ON;
[!WARNING] β οΈ
READ UNCOMMITTEDand theWITH (NOLOCK)hint are not βgo fasterβ switches. They allow dirty reads, and in MSSQL they can also return missing or duplicated rows if data moves around inside the table while it is being read. Never useNOLOCKon data anyone will act on. It is acceptable only for rough approximations β βroughly how many rows are in this log table.β
43.3 π Locking
| Lock type | Also called | Behaviour |
|---|---|---|
| Shared (S) | Read lock | Many readers can hold it together; blocks writers |
| Exclusive (X) | Write lock | Only one holder; blocks everyone |
| Update (U) | MSSQL | Held while deciding whether to update; prevents a common deadlock (two sessions stuck waiting for each other β 43.4) |
| Intent (IS/IX) | Β | A marker at table level saying βI hold row locks belowβ |
Lock size: a lock can cover one row, a page (a block of rows), or a whole table. Swapping many small locks for one big lock (lock escalation) is cheaper for the server to track, but blocks more people. MSSQL escalates to a table lock at roughly 5000 locks on one object β a common cause of sudden blocking during large updates. Batching your updates (Chapter 18) avoids it.
Explicit locking when you read a value and then change it:
-- π₯ MSSQL: take the update lock at read time
BEGIN TRANSACTION;
SELECT units_in_stock
FROM products WITH (UPDLOCK, ROWLOCK)
WHERE product_id = 5;
UPDATE products SET units_in_stock = units_in_stock - 1 WHERE product_id = 5;
COMMIT;
-- π¦ MySQL: SELECT ... FOR UPDATE
START TRANSACTION;
SELECT units_in_stock FROM products WHERE product_id = 5 FOR UPDATE;
UPDATE products SET units_in_stock = units_in_stock - 1 WHERE product_id = 5;
COMMIT;
[!TIP] π‘ Or avoid the problem entirely by making the update atomic:
UPDATE products SET units_in_stock = units_in_stock - 1 WHERE product_id = 5 AND units_in_stock >= 1; -- Then check the affected row count: 0 means there was no stock.This is a single atomic statement β no read-then-write gap exists, so no lost update is possible. When you can express the change as one statement, do.
43.4 π Deadlocks
[!NOTE] π In plain words: Two transactions each hold something the other needs. Neither can proceed. The database detects this and kills one of them so the other can finish.
Session A Session B
βββββββββββββββββββββββββ βββββββββββββββββββββββββ
UPDATE products (locks row 5)
UPDATE customers (locks row 1)
UPDATE customers (waits for B) ββββ
ββββ UPDATE products (waits for A)
π DEADLOCK β the engine kills one transaction
The cure β and it is genuinely this simple: always access tables in the same order.
-- β
EVERY procedure in your system touches: customers β orders β order_items β products
-- If all code follows one order, this class of deadlock cannot occur.
| Prevention technique | How it helps |
|---|---|
| Consistent object access order | Removes the circular wait entirely |
| Short transactions | Less time holding locks = smaller collision window |
| Correct indexes | Row locks instead of table scans locking everything |
| Lower isolation where safe | Fewer and shorter locks |
MVCC (READ_COMMITTED_SNAPSHOT, InnoDB) |
Readers stop blocking writers |
| Retry logic in the application | Deadlocks are normal; simply retry the cancelled transaction |
-- π₯ MSSQL: find recent deadlocks
SELECT XEventData.XEvent.value('(data/value)[1]', 'varchar(max)') AS deadlock_graph
FROM (
SELECT CAST(target_data AS XML) AS TargetData
FROM sys.dm_xe_session_targets st
JOIN sys.dm_xe_sessions s ON s.address = st.event_session_address
WHERE s.name = 'system_health' AND st.target_name = 'ring_buffer'
) AS Data
CROSS APPLY TargetData.nodes('RingBufferTarget/event[@name="xml_deadlock_report"]')
AS XEventData(XEvent);
-- π¦ MySQL: the most recent deadlock is always in the engine status
SHOW ENGINE INNODB STATUS;
-- Look for the "LATEST DETECTED DEADLOCK" section
-- Who is blocking whom, right now
SELECT * FROM performance_schema.data_locks;
SELECT * FROM sys.innodb_lock_waits;
[!TIP] π‘ Deadlocks are not bugs to be eliminated at all cost β they are a normal fact of concurrent systems. Every production application should catch the deadlock error (MSSQL 1205, MySQL 1213) and retry the transaction, typically 3 times with a short, slightly random pause between tries. Systems without retry logic show users random failures under load.
43.5 π Diagnosing blocking right now
-- π₯ MSSQL: who is blocking whom
SELECT
r.session_id,
r.blocking_session_id,
r.wait_type,
r.wait_time,
r.status,
t.text AS running_sql
FROM sys.dm_exec_requests r
CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) t
WHERE r.blocking_session_id <> 0;
-- Kill a runaway session (last resort, know what it is doing first)
-- KILL 57;
-- π¦ MySQL
SELECT * FROM performance_schema.processlist; -- SHOW PROCESSLIST still works, but reads a deprecated source
SELECT * FROM sys.session WHERE command <> 'Sleep';
SELECT * FROM sys.innodb_lock_waits;
-- KILL 1234;
π This chapter covered what the engine does. Chapter 63 covers what you must do β the lost update that no isolation level prevents, optimistic vs pessimistic concurrency, idempotency keys, and the queue pattern.
43.6 π§ͺ Try it yourself
- Open two sessions. In session 1, start a transaction and update a product without committing. In session 2, try to read that row. Observe the block in MSSQL and the non-block in MySQL.
- Reproduce a lost update by hand using two sessions and the read-then-write pattern.
- Fix it with
FOR UPDATE/UPDLOCK. - Deliberately create a deadlock with two sessions updating two tables in opposite order. Read the error message.
- Rewrite the stock decrement as a single atomic
UPDATEand explain why it needs no lock hint.
π§ In practice β isolation levels, locking, and deadlocks
How to use it. Set the level with
SET TRANSACTION ISOLATION LEVEL .... Higher levels prevent more anomalies β dirty reads, non-repeatable reads, phantoms β at the cost of more blocking. SQL Server defaults toREAD COMMITTED(locking); MySQL InnoDB defaults toREPEATABLE READ. Expected result: a deliberate, documented trade-off between correctness under concurrency and throughput.When to use it. When you observe blocking, deadlocks, or results that change within one transaction β and before that, whenever money or stock is involved.
Where to use it. High-concurrency systems. Scenario: two checkouts buy the last item simultaneously. At the default level both can read stock as 1 and both decrement it, overselling. The fix is either a higher isolation level or an explicit locking read (
UPDLOCK/SELECT ... FOR UPDATE) β the pattern in Chapter 63.When not to use it. Do not reach for
SERIALIZABLEas a blanket fix β it serialises work and can turn a concurrency bug into a throughput collapse. Above all, never useREAD UNCOMMITTEDorWITH (NOLOCK)to make reports faster: it reads uncommitted data that may be rolled back, and can return rows twice or skip them entirely during page splits. It is not a performance setting; it is a correctness trade nobody documented.Best practices. Deadlocks are normal in a busy system and your application must retry them, not just log them. Reduce their frequency by keeping transactions short, touching tables in a consistent order, and indexing well β many deadlocks are caused by scans taking more locks than necessary. Consider snapshot isolation (
READ_COMMITTED_SNAPSHOTin SQL Server) when readers block writers; it coststempdbbut removes a whole class of blocking.
44. MERGE and UPSERT
| ποΈ Level | β±οΈ Time | π― After this chapter you canβ¦ |
|---|---|---|
| π‘ Intermediate | 25 min | Insert new rows and update existing ones in one go Β· Sync a table from a data feed Β· Avoid the dangerous REPLACE |
[!NOTE] π In plain words: βInsert it if it is new, update it if it already exists.β This is called an upsert, and it is one of the most common real-world requirements β syncing data, importing files, keeping a summary table up to date.
π Analogy: Updating your phoneβs contacts from a list. If the person is already in your phone, you update their number; if not, you add them as a new contact.
44.1 π₯ MSSQL: MERGE
The examples in this chapter read a two-row supplier feed. Load it into the staging_products table from Chapter 12:
-- β
Works in BOTH
DELETE FROM staging_products;
INSERT INTO staging_products (product_name, category_id, supplier_id, unit_price, units_in_stock) VALUES
('UltraBook Pro 14', 1, 1, 1449.00, 30), -- already in products: price and stock changed
('Brand New Gadget', 4, 2, 59.00, 100); -- not in products yet
MERGE INTO products AS target
USING staging_products AS source
ON target.product_name = source.product_name
WHEN MATCHED AND (
target.unit_price <> source.unit_price
OR target.units_in_stock <> source.units_in_stock
) THEN
UPDATE SET
target.unit_price = source.unit_price,
target.units_in_stock = source.units_in_stock
WHEN NOT MATCHED BY TARGET THEN
INSERT (product_name, category_id, supplier_id, unit_price, units_in_stock)
VALUES (source.product_name, source.category_id, source.supplier_id,
source.unit_price, source.units_in_stock)
WHEN NOT MATCHED BY SOURCE THEN
UPDATE SET target.discontinued = 1 -- no longer in the feed: retire it
OUTPUT $action, inserted.product_id, inserted.product_name; -- π‘ report what happened
Result on ShopDB (with the two-row feed above β one changed product, one new one):
| $action | product_id | product_name |
|---|---|---|
| INSERT | 19 | Brand New Gadget |
| UPDATE | 1 | UltraBook Pro 14 |
| UPDATE | 2 | UltraBook Air 13 |
| β¦ | β¦ | 16 more UPDATE rows, products 3β18 |
[!WARNING] β οΈ Read those extra rows carefully. Every product that is not in the feed matched
WHEN NOT MATCHED BY SOURCEand was retired withdiscontinued = 1β 17 of the 18 existing products. That is exactly right when the feed is the complete catalogue, and exactly wrong when it is a partial update. Only includeWHEN NOT MATCHED BY SOURCEwhen the source really is the whole truth.
[!WARNING] β οΈ A bare
OUTPUTclause fails the moment the target table has a trigger. Ifproductscarries the audit trigger from Chapter 39, the statement above dies with:Msg 334: The target table 'target' of the DML statement cannot have any enabled triggers if the statement contains an OUTPUT clause without INTO clause.The fix is to send the output somewhere β a table variable or temp table:
DECLARE @changes TABLE (action_taken NVARCHAR(10), product_id INT, product_name NVARCHAR(120)); MERGE INTO products WITH (HOLDLOCK) AS target USING staging_products AS source ON target.product_name = source.product_name WHEN MATCHED AND target.unit_price <> source.unit_price THEN UPDATE SET target.unit_price = source.unit_price WHEN NOT MATCHED BY TARGET THEN INSERT (product_name, category_id, supplier_id, unit_price, units_in_stock) VALUES (source.product_name, source.category_id, source.supplier_id, source.unit_price, source.units_in_stock) OUTPUT $action, inserted.product_id, inserted.product_name INTO @changes; -- β INTO SELECT * FROM @changes;This applies to
OUTPUTon plainINSERT,UPDATE, andDELETEtoo β it is not aMERGEquirk. Any table with a trigger requiresOUTPUT ... INTO.
The three match clauses:
| Clause | Meaning |
|---|---|
WHEN MATCHED |
The row exists in both β usually UPDATE |
WHEN NOT MATCHED [BY TARGET] |
In the source only β INSERT |
WHEN NOT MATCHED BY SOURCE |
In the target only β UPDATE or DELETE |
[!WARNING] β οΈ
MERGEhas a long history of bugs and gotchas in SQL Server β incorrect results with certain index/trigger combinations, unexpected deadlocks, and constraint violations under concurrency. Many senior SQL Server professionals deliberately avoid it. If you use it, always addWITH (HOLDLOCK)on the target so it stays correct when many users run it at once:-- π₯ MSSQL: the hint goes on the target, right before its alias -- MERGE INTO products WITH (HOLDLOCK) AS target ... (the full statement is shown above)
44.2 π¦ MySQL: INSERT β¦ ON DUPLICATE KEY UPDATE
-- β
MySQL: requires a UNIQUE or PRIMARY KEY on the matching column
-- ShopDB has no unique key on product_name yet, so add one first β without it,
-- every "upsert" below silently inserts a duplicate instead of updating
ALTER TABLE products ADD CONSTRAINT uq_products_name UNIQUE (product_name);
INSERT INTO products (product_name, category_id, supplier_id, unit_price, units_in_stock)
VALUES ('Zenith Phone 13', 2, 3, 999.00, 50) AS new
ON DUPLICATE KEY UPDATE
unit_price = new.unit_price, -- older code writes VALUES(unit_price): deprecated since 8.0.20
units_in_stock = new.units_in_stock;
-- Run it a second time: the row now exists, so this UPDATES it (the column list may differ)
INSERT INTO products (product_name, category_id, unit_price, units_in_stock)
VALUES ('Zenith Phone 13', 2, 999.00, 50) AS new
ON DUPLICATE KEY UPDATE
unit_price = new.unit_price,
units_in_stock = new.units_in_stock;
-- Bulk upsert from a staging table (8.0.20+ form: alias the SELECT as a derived table)
INSERT INTO products (product_name, category_id, supplier_id, unit_price, units_in_stock)
SELECT * FROM (
SELECT product_name, category_id, supplier_id, unit_price, units_in_stock
FROM staging_products
) AS new
ON DUPLICATE KEY UPDATE
unit_price = new.unit_price,
units_in_stock = new.units_in_stock;
Other MySQL variants:
-- REPLACE: DELETE the old row then INSERT a new one
-- (product 4 has never been ordered β try product 5 and the FOREIGN KEY from order_items blocks the DELETE half)
REPLACE INTO products (product_id, product_name, category_id, unit_price)
VALUES (4, 'Legacy Netbook 10', 1, 249.00);
[!WARNING] β οΈ
REPLACEis genuinely dangerous. It deletes the existing row (firing delete triggers and cascading foreign keys!) and inserts a brand new one with a new auto-increment value. Columns you did not supply revert to their defaults. Child rows can be cascade-deleted. PreferON DUPLICATE KEY UPDATEin almost every case.
44.3 β The portable upsert (works everywhere)
Concurrency contract: the update-then-insert shape below needs a unique key and engine-specific locking or a duplicate-key retry. A transaction alone does not serialize two sessions that both see a missing row. Prefer a tested engine-native upsert or serialize the key range before deciding to insert.
-- β
Works in BOTH: update first, insert what did not exist
-- Run the two statements inside one transaction β
-- in MSSQL: BEGIN TRANSACTION; β¦ COMMIT; in MySQL: START TRANSACTION; β¦ COMMIT;
UPDATE products
SET unit_price = (SELECT s.unit_price FROM staging_products s
WHERE s.product_name = products.product_name),
units_in_stock = (SELECT s.units_in_stock FROM staging_products s
WHERE s.product_name = products.product_name)
WHERE EXISTS (SELECT 1 FROM staging_products s
WHERE s.product_name = products.product_name);
INSERT INTO products (product_name, category_id, supplier_id, unit_price, units_in_stock)
SELECT s.product_name, s.category_id, s.supplier_id, s.unit_price, s.units_in_stock
FROM staging_products s
WHERE NOT EXISTS (
SELECT 1 FROM products p WHERE p.product_name = s.product_name
);
[!TIP] π‘ Order matters:
UPDATEfirst, thenINSERT. If you insert first, the newly inserted rows then match the update and get pointlessly updated. Updating first touches only the pre-existing rows.
44.4 π― Real-world upsert scenarios
β Daily inventory feed from a supplier β the bulk upsert shown above.
β‘ A page-view counter that must not lose counts:
-- β
MySQL
CREATE TABLE page_views (
page_url VARCHAR(200) NOT NULL,
view_date DATE NOT NULL,
views INT NOT NULL,
PRIMARY KEY (page_url, view_date) -- π the key the upsert matches on
);
INSERT INTO page_views (page_url, view_date, views)
VALUES ('/products/5', CURDATE(), 1)
ON DUPLICATE KEY UPDATE views = views + 1;
-- β
MSSQL: update first, insert only if nothing was updated
CREATE TABLE page_views (
page_url VARCHAR(200) NOT NULL,
view_date DATE NOT NULL,
views INT NOT NULL,
CONSTRAINT pk_page_views PRIMARY KEY (page_url, view_date)
);
GO
SET XACT_ABORT ON;
BEGIN TRY
BEGIN TRANSACTION;
UPDATE page_views WITH (UPDLOCK, SERIALIZABLE) SET views = views + 1
WHERE page_url = '/products/5' AND view_date = CAST(GETDATE() AS DATE);
IF @@ROWCOUNT = 0
INSERT INTO page_views (page_url, view_date, views)
VALUES ('/products/5', CAST(GETDATE() AS DATE), 1);
COMMIT;
END TRY
BEGIN CATCH
IF XACT_STATE() <> 0 ROLLBACK;
THROW;
END CATCH;
β’ Maintaining a summary/cache table after each order:
-- β
MSSQL
CREATE TABLE customer_summary (
customer_id INT NOT NULL PRIMARY KEY,
order_count INT NOT NULL,
last_order DATE NOT NULL
);
GO
MERGE INTO customer_summary WITH (HOLDLOCK) AS t
USING (
SELECT customer_id, COUNT(*) AS order_count, MAX(order_date) AS last_order
FROM orders GROUP BY customer_id
) AS s ON s.customer_id = t.customer_id
WHEN MATCHED THEN UPDATE SET t.order_count = s.order_count, t.last_order = s.last_order
WHEN NOT MATCHED THEN INSERT (customer_id, order_count, last_order)
VALUES (s.customer_id, s.order_count, s.last_order);
44.5 π― When to use which upsert
| Situation | π₯ MSSQL | π¦ MySQL |
|---|---|---|
| One row, might exist | MERGE, or IF EXISTS β¦ ELSE β¦ |
INSERT β¦ ON DUPLICATE KEY UPDATE |
| Bulk load from a staging table | MERGE WITH (HOLDLOCK) |
INSERT β¦ SELECT β¦ ON DUPLICATE KEY UPDATE |
| A counter that must never lose a hit | UPDATE β¦ ; IF @@ROWCOUNT = 0 INSERT |
ON DUPLICATE KEY UPDATE n = n + 1 |
| You must also retire rows missing from the feed | MERGE + WHEN NOT MATCHED BY SOURCE |
Two statements |
| You want portable code | Two statements: UPDATE then INSERT β¦ WHERE NOT EXISTS |
same |
| High concurrency, correctness critical | β οΈ MERGE needs HOLDLOCK; many teams avoid it |
ON DUPLICATE KEY UPDATE is atomic |
44.6 π§ͺ Try it yourself
- Create a
staging_productstable with 3 existing and 2 new products. Upsert it in both dialects. - In MySQL, compare
REPLACE INTOandON DUPLICATE KEY UPDATEon a row that has child records. Note what happens to the children. - Write the portable two-statement upsert inside a transaction.
- Build a
page_viewscounter table and increment the same URL 5 times.
π§ In practice β MERGE and UPSERT
How to use it. βInsert if new, update if it already exists.β MySQL has
INSERT ... ON DUPLICATE KEY UPDATE; SQL Server hasMERGE. Both need a unique key to decide what βalready existsβ means. Expected result: a load you can re-run without creating duplicates β an idempotent operation.When to use it. Synchronising data from an external source: a nightly supplier feed, an imported price list, a replicated table.
Where to use it. ETL and integration. Scenario: a supplier sends a full product file every night. An upsert keyed on the supplierβs product code inserts new products and updates changed ones, so re-running a failed job is safe rather than catastrophic.
When not to use it. Be cautious with SQL Serverβs
MERGE. It has a long history of well-documented bugs and concurrency hazards, and the common advice from experienced practitioners is to prefer an explicitUPDATEfollowed by anINSERT, inside a transaction, for anything critical. Do not useMERGEat all without a unique index on the join key β without one it can match the same target row twice and fail unpredictably.Best practices. Make every load idempotent and test it by running it twice β if the row count changes on the second run, it is not idempotent. Define the matching key explicitly, and decide deliberately what happens to rows present in the target but absent from the source: deleting them is a common default and a common accident.
45. Error handling
| ποΈ Level | β±οΈ Time | π― After this chapter you canβ¦ |
|---|---|---|
| π‘ Intermediate | 25 min | Catch errors and clean up Β· Raise your own clear error messages Β· Log errors that survive a rollback Β· Retry after a deadlock |
[!NOTE] π In plain words: Things go wrong: constraint violations, deadlocks, division by zero, missing rows. Error handling lets your code notice, clean up, and report clearly instead of leaving a half-finished mess.
π Analogy: A smoke alarm and a fire exit plan. You hope you never need them, but when something goes wrong, they decide whether you get a small, controlled problem or a disaster.
45.1 π₯ MSSQL: TRY β¦ CATCH
BEGIN TRY
BEGIN TRANSACTION;
INSERT INTO orders (customer_id, order_date, status)
VALUES (9999, '2026-09-09', 'Pending'); -- β no such customer
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;
SELECT
ERROR_NUMBER() AS error_number,
ERROR_SEVERITY() AS severity,
ERROR_STATE() AS state,
ERROR_PROCEDURE() AS procedure_name,
ERROR_LINE() AS line_number,
ERROR_MESSAGE() AS message;
END CATCH;
The error functions:
| Function | Returns |
|---|---|
ERROR_NUMBER() |
The numeric error code (547 = FK violation, 2627 = PK violation, 1205 = deadlock) |
ERROR_MESSAGE() |
The human-readable text |
ERROR_SEVERITY() |
0β25; 16 is a normal user error |
ERROR_LINE() |
Which line inside the procedure failed |
ERROR_PROCEDURE() |
Which procedure it happened in |
Raising your own errors:
-- β
Preferred (2012+): THROW
THROW 50001, 'Customer credit limit exceeded.', 1;
GO
-- Re-throw the current error from inside a CATCH block
BEGIN TRY
THROW 50002, 'Something went wrong.', 1;
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;
THROW; -- preserves the original number and message
END CATCH;
GO
-- Older: RAISERROR, which supports printf-style message formatting
DECLARE @cust INT = 9999;
RAISERROR('Customer %d was not found.', 16, 1, @cust);
[!TIP] π‘ Prefer
THROWoverRAISERRORin new code.THROWpreserves the original error number, always uses severity 16, and re-raises cleanly.RAISERRORis only needed for fill-in-the-blank messages such as'Customer %d was not found.'.
Logging errors properly:
CREATE TABLE error_log (
error_id INT IDENTITY(1,1) PRIMARY KEY,
error_number INT,
error_message NVARCHAR(2048),
procedure_name NVARCHAR(128),
line_number INT,
occurred_at DATETIME2(0) NOT NULL DEFAULT SYSDATETIME(),
occurred_by NVARCHAR(128) NOT NULL DEFAULT SUSER_SNAME()
);
GO
CREATE OR ALTER PROCEDURE usp_safe_operation
AS
BEGIN
SET NOCOUNT ON;
SET XACT_ABORT ON;
BEGIN TRY
BEGIN TRANSACTION;
-- work here
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;
-- β
Log AFTER the rollback, or the log row rolls back too!
INSERT INTO error_log (error_number, error_message, procedure_name, line_number)
VALUES (ERROR_NUMBER(), ERROR_MESSAGE(), ERROR_PROCEDURE(), ERROR_LINE());
THROW;
END CATCH;
END;
GO
[!WARNING] β οΈ Log after the rollback, never before. If you insert the log row inside the failed transaction and then roll back, the log entry disappears along with everything else β and you are left debugging an error that left no trace.
45.2 π¦ MySQL: DECLARE β¦ HANDLER
-- The MySQL version of the error_log table from 45.1
CREATE TABLE error_log (
error_id INT AUTO_INCREMENT PRIMARY KEY,
error_number INT,
error_message VARCHAR(2048),
procedure_name VARCHAR(128),
line_number INT,
occurred_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
occurred_by VARCHAR(128) NOT NULL DEFAULT (CURRENT_USER())
) ENGINE=InnoDB;
DELIMITER $$
CREATE PROCEDURE usp_safe_operation()
BEGIN
DECLARE v_errno INT;
DECLARE v_msg VARCHAR(512);
-- EXIT = stop the procedure. CONTINUE = keep going after handling.
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
GET DIAGNOSTICS CONDITION 1
v_errno = MYSQL_ERRNO,
v_msg = MESSAGE_TEXT;
ROLLBACK;
INSERT INTO error_log (error_number, error_message, procedure_name)
VALUES (v_errno, v_msg, 'usp_safe_operation');
RESIGNAL; -- re-raise to the caller
END;
START TRANSACTION;
-- work here
COMMIT;
END$$
DELIMITER ;
Handler types (SQLSTATE is a standard five-character error code; the plain numbers are MySQLβs own error codes):
| Declaration | Catches |
|---|---|
FOR SQLEXCEPTION |
Any error (SQLSTATE not starting 00, 01, or 02) |
FOR SQLWARNING |
Warnings (SQLSTATE 01xxx) |
FOR NOT FOUND |
No more rows (SQLSTATE 02xxx) β used with cursors |
FOR SQLSTATE '23000' |
A specific SQLSTATE (23000 = integrity violation) |
FOR 1062 |
A specific MySQL error number (1062 = duplicate key) |
-- Handling a specific error gracefully
DELIMITER $$
CREATE PROCEDURE usp_add_category(IN p_name VARCHAR(50))
BEGIN
DECLARE CONTINUE HANDLER FOR 1062 -- duplicate key
BEGIN
SELECT CONCAT('Category "', p_name, '" already exists.') AS message;
END;
INSERT INTO categories (category_name) VALUES (p_name);
END$$
DELIMITER ;
Raising your own errors:
SIGNAL SQLSTATE '45000' -- 45000 = "unhandled user-defined exception"
SET MESSAGE_TEXT = 'Customer credit limit exceeded.',
MYSQL_ERRNO = 1644;
-- Re-raise the current error. RESIGNAL is only valid INSIDE a DECLARE ... HANDLER
-- block, exactly as usp_safe_operation uses it above:
-- RESIGNAL;
45.3 π’ The error codes you will meet
| Situation | π₯ MSSQL | π¦ MySQL |
|---|---|---|
| Duplicate key | 2627 / 2601 | 1062 |
| Foreign key violation | 547 | 1452 (insert) / 1451 (delete) |
| NULL in a NOT NULL column | 515 | 1048 |
| String truncation | 8152 / 2628 | 1406 |
| Deadlock victim | 1205 | 1213 |
| Lock wait timeout | 1222 | 1205 |
| Divide by zero | 8134 | 1365 |
| Conversion failed | 245 | 1292 |
[!TIP] π‘ Note the confusing overlap: 1205 means βdeadlockβ in MSSQL and βlock wait timeoutβ in MySQL. If you write retry logic for both engines, be precise about which code you are matching.
45.4 π Retry logic for deadlocks
-- π₯ MSSQL: retry a deadlocked transaction up to 3 times
DECLARE @retry INT = 3;
WHILE @retry > 0
BEGIN
BEGIN TRY
BEGIN TRANSACTION;
-- the work that might deadlock
UPDATE products SET units_in_stock = units_in_stock - 1 WHERE product_id = 5;
UPDATE orders SET status = 'Paid' WHERE order_id = 1022;
COMMIT TRANSACTION;
SET @retry = 0; -- success, stop looping
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;
IF ERROR_NUMBER() = 1205 AND @retry > 1 -- deadlock victim: try again
BEGIN
SET @retry = @retry - 1;
WAITFOR DELAY '00:00:00.100'; -- short backoff
END
ELSE
BEGIN
THROW; -- a real error: give up
END
END CATCH;
END;
[!TIP] π‘ In production, retry logic usually belongs in the application layer, where you can add growing, slightly random waits between retries, automatic pausing when a system keeps failing, and proper logging. But knowing how to do it in T-SQL is valuable for batch jobs and ETL that run entirely inside the database.
45.5 π― When to handle an error β and when to let it fly
| Situation | Handle it? |
|---|---|
| A deadlock (1205 π₯ / 1213 π¦) | β Catch and retry β it is expected under load |
| A duplicate key on an βinsert if newβ path | β Catch and turn it into an update, or use an upsert |
| A business rule violation you can explain to the user | β
Catch, then THROW/SIGNAL a clear message |
| A foreign key violation from bad input | β Catch, log, return a friendly message |
| A genuine bug (invalid column, syntax) | β Let it fail loudly β hiding it costs you days later |
| Anything you cannot actually fix | β Log it and re-raise (THROW / RESIGNAL) |
[!TIP] π‘ The rule: catch what you can act on, log everything, and never swallow an error silently. An empty
CATCHblock is the most expensive four lines in any codebase β it converts a loud failure into silent data corruption.
45.6 π§ͺ Try it yourself
- Write a procedure that inserts an order for a non-existent customer, catches the FK error, and logs it.
- In MySQL, write a handler that catches duplicate-key errors and returns a friendly message.
- Raise a custom error with your own message in both dialects.
- Prove that logging inside the failed transaction loses the log row, then fix it.
π§ In practice β error handling
How to use it. SQL Server:
BEGIN TRY ... END TRY BEGIN CATCH ... END CATCH, withERROR_MESSAGE()andTHROWto re-raise. MySQL:DECLARE ... HANDLER FOR SQLEXCEPTIONinside a procedure. Expected result: a failure that rolls back cleanly and reports something a human can act on, rather than leaving a half-applied change.When to use it. In every stored procedure that modifies data, and in every batch job that must either finish or leave nothing behind.
Where to use it. Transactional procedures and scheduled jobs. Scenario:
usp_place_ordercatches a stock-check failure, rolls back the transaction, and raises a specific message. The application then shows βOut of stockβ instead of a raw engine error, and β crucially β no partial order remains.When not to use it. Do not swallow errors. A
CATCHblock that logs and continues leaves the caller believing the work succeeded, which is worse than failing loudly. Do not rely on error handling to substitute for constraints either β catching a violation is a fallback, while the constraint is what makes the bad state impossible.Best practices. Always check transaction state before rolling back (
XACT_STATE()in SQL Server); rolling back when no transaction is active is itself an error. Re-raise after cleanup so the caller knows. Log enough context to diagnose β the statement, the parameters, the time β but never log passwords, tokens, or personal data, because logs are routinely copied to places with weaker access control than the database.
β Checkpoint β after Chapter 45 Β· you can keep data correct under load
[!IMPORTANT] Everything up to here was about getting the right answer. This part is about still getting it when a thousand people act at once β and about what the database guarantees when things fail.
π£οΈ Teach it back
What is it? Why does it matter? How does it work? Can I give an example? β for each of:
- ACID, and what each letter buys you (Ch 42)
- Isolation levels and the anomalies they prevent (Ch 43)
- Deadlocks, and why retry is part of the design (Ch 43)
- Views, stored procedures, and triggers β and their costs (Ch 36β39)
- Upsert and idempotency (Ch 44)
π§ͺ Self-check questions
- Why must placing an order be a transaction?
- Someone suggests adding
WITH (NOLOCK)to speed up the reports. What do you say? - Two checkouts buy the last item at the same moment and both succeed. Name two ways to prevent it.
- What is the strongest argument against putting business logic in triggers?
- What does βidempotentβ mean for a nightly import, and how do you test it?
- Your application logs deadlocks nightly. Is that a bug to eliminate?
π Sample answers
-
Because it touches several tables and a partial result is a wrong result. Inserting the order, inserting its lines, and decrementing stock must all happen or none of them. Without atomicity a crash between steps leaves an order for goods nobody reserved β discovered days later by the warehouse.
-
That it is not a performance setting, it is a correctness trade nobody wrote down.
READ UNCOMMITTEDreads data that may be rolled back, and during page splits it can return the same row twice or skip it entirely. If reports are blocking writers, the right answers are snapshot isolation, better indexing, or a read replica. -
An atomic conditional update β
UPDATE ... SET stock = stock - 1 WHERE product_id = ? AND stock >= 1, where the second caller updates zero rows β or a locking read (WITH (UPDLOCK)/SELECT ... FOR UPDATE) that makes the second caller wait. The atomic statement is simpler and needs no retry logic. See Chapter 63. -
They are invisible. A developer reading the application sees one
UPDATEand has no way to know that three other tables changed or that a slow operation ran inside their transaction. Triggers are excellent for auditing, precisely because auditing should happen regardless of who made the change β and poor for logic, for the same reason. -
Running it twice produces the same result as running it once. You test it by literally running it twice and checking the row counts and values are unchanged. An upsert keyed on a unique column gives you this; a plain
INSERTdoes not, which is why a retried job creates duplicates. -
No β deadlocks are a normal condition in a busy system. The engine detects the cycle and kills the cheaper transaction precisely so the other can proceed. The bug would be an application that does not retry the victim. You reduce their frequency with short transactions, consistent lock ordering, and good indexes, but you do not eliminate them.
π― Give a simple example
Explain to a non-technical colleague why a bank transfer needs a transaction, using no database words. Then say what βisolationβ adds that atomicity alone does not.
| Part index | Prerequisites | Previous | Next | Full course |