// SQL snippet

Preview an id remap before running it

Join the mapping table to the child's foreign key; the matched rows are exactly the UPDATE's targets, and unmatched map entries are remaps that would do nothing.

Main statement
All engines

The task

Merging two customer databases requires renumbering ids: a mapping table old_order_id -> new_order_id exists, and you want to verify what it touches before the UPDATE runs, including map rows that point at children no longer present.

The snippet

Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.

All engines
SELECT oi.id AS order_item_id,
       oi.order_id AS current_order_id,
       m.new_order_id AS will_become
FROM order_items oi
JOIN order_id_map m ON m.old_order_id = oi.order_id
ORDER BY oi.order_id, oi.id;

Fonctionnement

The join between the child table and the mapping table is the UPDATE's WHERE clause in preview form: every matched row is one the remap would rewrite, and the two value columns show the before and after id. Rows in the map that match nothing can be listed with a LEFT JOIN from the map side. They are either stale map entries or children that were already cleaned up.

Variations

Map entries that would match nothing

SELECT m.old_order_id, m.new_order_id
FROM order_id_map m
WHERE NOT EXISTS (
  SELECT 1 FROM order_items oi WHERE oi.order_id = m.old_order_id
);

Collisions: target id already in use

SELECT m.old_order_id, m.new_order_id, COUNT(*) AS conflicting_rows
FROM order_id_map m
JOIN order_items oi ON oi.order_id = m.new_order_id
GROUP BY m.old_order_id, m.new_order_id
ORDER BY conflicting_rows DESC;

Questions that come up

Why preview instead of just running the UPDATE?

Because a wrong id remap fails silently: as long as the wrong target id exists in orders, the foreign key is satisfied and the line simply belongs to someone else's order. Only a target that does not exist, or a unique constraint on the child, makes the UPDATE fail. The preview shows the exact row set and the before/after pairs; check them, then run the UPDATE in a transaction and compare its row count with the preview.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.