// SQL snippet

Preview a migration diff between tables

A symmetric difference shows rows added or dropped by the migration; a per-key join shows rows the migration rewrote.

Main statement
All engines

The task

The migration copied orders into orders_new with a schema change. Before switching reads over, you need the diff: rows that did not make it, rows that appeared from nowhere, and rows whose values were transformed.

The snippet

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

All engines
SELECT MIN(source) AS present_in, id, status, total
FROM (
  SELECT id, status, total, 'old' AS source FROM orders_old
  UNION ALL
  SELECT id, status, total, 'new' AS source FROM orders_new
) combined
GROUP BY id, status, total
HAVING COUNT(*) = 1
ORDER BY id, present_in;

仕組み

Union both tables with a source tag, group by every column, and keep groups of 1: rows found on one side only. present_in names the side. Rows that the migration legitimately changed (a type conversion, a default applied) show up here too. The per-key join variant tells the two cases apart.

Variations

Changed rows, old vs new side by side

SELECT o.id,
       o.status AS old_status, n.status AS new_status,
       o.total AS old_total, n.total AS new_total
FROM orders_old o
JOIN orders_new n ON n.id = o.id
WHERE o.status <> n.status OR o.total <> n.total
ORDER BY o.id;

Rows missing from the target entirely

SELECT o.id
FROM orders_old o
WHERE NOT EXISTS (
  SELECT 1 FROM orders_new n WHERE n.id = o.id
)
ORDER BY o.id;

Questions that come up

The diff is non-empty. Is the migration wrong?

Not necessarily: transformations are the point of many migrations. What matters is that every diff row is expected. Group the findings into explained (documented transformation) and unexplained (bug), and gate the cutover on an empty unexplained set, not on an empty diff.

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.