Data modification & MERGE
Concept  ·  SQL & Querying

USING / correlated DML scopes which rows die — get the join predicate wrong and you delete too much.

Joined DML is set-based editing — powerful because the target set is computed. Three disciplines keep it safe: preview the set (run the join as a SELECT first — the same rows the DML will touch); check the grain (a target row matching two source rows makes UPDATE-FROM pick one arbitrarily — pre-aggregate the source); respect the blast radius (UPDATE/DELETE without WHERE is the whole table).

See it break
stock
skuqty
A10
B5
disc
sku
B
The trap
DELETE FROM stock ;

SELECT
  sku,
  qty
FROM
  stock
ORDER BY
  sku;
The fix
DELETE FROM stock USING disc d
WHERE
  stock.sku = d.sku;

SELECT
  sku,
  qty
FROM
  stock
ORDER BY
  sku;

The shrinkage DELETE with no predicate emptied the whole stock table — a joined DELETE scopes which rows die by its predicate, so a missing one deletes everything; DELETE ... USING with the join key removes only the matched rows.

The rule

SELECT-preview → grain check → DML, inside a transaction.

Spellings vary (USING / FROM / MERGE / correlated subqueries as the portable floor); the preview-grain-radius discipline doesn't.

Shows up elsewhere
MERGE with a duplicated source keyTransactions at the statement-batch level
Try one →Prove it in practice →