// SQL snippet

Find rows that differ between two tables

Stack both tables with UNION ALL, group by every column, and keep groups whose total count is 1: rows that exist on one side only.

Main statement
All engines

The task

You just rewrote the products load and want proof that products_staging matches the live products table row for row. Rows present in only one side, or with any changed value, must surface.

The snippet

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

All engines
SELECT MIN(source) AS found_in, sku, name, price
FROM (
  SELECT sku, name, price, 'staging' AS source
  FROM products_staging
  UNION ALL
  SELECT sku, name, price, 'live' AS source
  FROM products
) combined
GROUP BY sku, name, price
HAVING COUNT(*) = 1
ORDER BY sku, found_in;

So funktioniert es

The inner UNION ALL concatenates both tables with a tag. Grouping over every column collapses matched pairs into groups of 2; rows that differ in any column, or exist on one side only, form groups of 1, which HAVING keeps. MIN(source) tells you which side the odd row came from. Because GROUP BY treats NULLs as equal, a NULL price on both sides counts as a match, which the changed-rows variant's <> comparison does not: there a NULL on either side makes the row disappear.

Variations

Rows changed, old and new side by side

SELECT o.sku, o.name AS old_name, o.price AS old_price,
       n.name AS new_name, n.price AS new_price
FROM products o
JOIN products_staging n ON n.sku = o.sku
WHERE o.name <> n.name OR o.price <> n.price;

EXCEPT form (SQL Server, PostgreSQL, SQLite, MySQL 8.0.31+, Oracle 21c+; MINUS on older Oracle)

SQL Server PostgreSQL MySQL SQLite Oracle
SELECT sku, name, price FROM products
EXCEPT
SELECT sku, name, price FROM products_staging;

Questions that come up

What if each table can contain internal duplicates?

The COUNT(*) = 1 trick assumes no table repeats a row internally: one row in each side cancels out to 2. If duplicates within a table are possible, first compare per sku with the changed-rows variant, or count occurrences per row per side and compare the two counts explicitly instead of relying on the union trick.

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.