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, one INSERT, one DELETE ❌ 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/DELETE you 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 UPDATE in 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 TRANSACTION before you type the UPDATE or DELETE. Run it, check the affected row count and a verification SELECT, and only then COMMIT. 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, and TRUNCATE all 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 = 2 or 0 makes 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

  1. Start a transaction, delete all of order_items, run a SELECT COUNT(*), then roll back and count again.
  2. Use savepoints to insert an order, insert a bad item, roll back to the savepoint, and still commit the order.
  3. In MySQL, prove that a CREATE TABLE inside a transaction commits your earlier insert.
  4. 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, with ROLLBACK on 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 COMMITTED using locks β€” readers block writers and writers block readers.
  • MySQL/InnoDB: REPEATABLE READ using 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_SNAPSHOT database 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 UNCOMMITTED and the WITH (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 use NOLOCK on 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

  1. 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.
  2. Reproduce a lost update by hand using two sessions and the read-then-write pattern.
  3. Fix it with FOR UPDATE / UPDLOCK.
  4. Deliberately create a deadlock with two sessions updating two tables in opposite order. Read the error message.
  5. Rewrite the stock decrement as a single atomic UPDATE and 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 to READ COMMITTED (locking); MySQL InnoDB defaults to REPEATABLE 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 SERIALIZABLE as a blanket fix β€” it serialises work and can turn a concurrency bug into a throughput collapse. Above all, never use READ UNCOMMITTED or WITH (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_SNAPSHOT in SQL Server) when readers block writers; it costs tempdb but 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 SOURCE and was retired with discontinued = 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 include WHEN NOT MATCHED BY SOURCE when the source really is the whole truth.

[!WARNING] ⚠️ A bare OUTPUT clause fails the moment the target table has a trigger. If products carries 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 OUTPUT on plain INSERT, UPDATE, and DELETE too β€” it is not a MERGE quirk. Any table with a trigger requires OUTPUT ... 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] ⚠️ MERGE has 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 add WITH (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] ⚠️ REPLACE is 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. Prefer ON DUPLICATE KEY UPDATE in 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: UPDATE first, then INSERT. 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

  1. Create a staging_products table with 3 existing and 2 new products. Upsert it in both dialects.
  2. In MySQL, compare REPLACE INTO and ON DUPLICATE KEY UPDATE on a row that has child records. Note what happens to the children.
  3. Write the portable two-statement upsert inside a transaction.
  4. Build a page_views counter 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 has MERGE. 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 explicit UPDATE followed by an INSERT, inside a transaction, for anything critical. Do not use MERGE at 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 THROW over RAISERROR in new code. THROW preserves the original error number, always uses severity 16, and re-raises cleanly. RAISERROR is 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 CATCH block is the most expensive four lines in any codebase β€” it converts a loud failure into silent data corruption.

45.6 πŸ§ͺ Try it yourself

  1. Write a procedure that inserts an order for a non-existent customer, catches the FK error, and logs it.
  2. In MySQL, write a handler that catches duplicate-key errors and returns a friendly message.
  3. Raise a custom error with your own message in both dialects.
  4. 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, with ERROR_MESSAGE() and THROW to re-raise. MySQL: DECLARE ... HANDLER FOR SQLEXCEPTION inside 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_order catches 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 CATCH block 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
  1. Why must placing an order be a transaction?
  2. Someone suggests adding WITH (NOLOCK) to speed up the reports. What do you say?
  3. Two checkouts buy the last item at the same moment and both succeed. Name two ways to prevent it.
  4. What is the strongest argument against putting business logic in triggers?
  5. What does β€œidempotent” mean for a nightly import, and how do you test it?
  6. Your application logs deadlocks nightly. Is that a bug to eliminate?
πŸ“ Sample answers
  1. 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.

  2. That it is not a performance setting, it is a correctness trade nobody wrote down. READ UNCOMMITTED reads 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.

  3. 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.

  4. They are invisible. A developer reading the application sees one UPDATE and 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.

  5. 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 INSERT does not, which is why a retried job creates duplicates.

  6. 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