Query for a one-off report
WITH differences AS (
SELECT o.id, 'only_source' AS status,
o.price_cents AS source_price,
NULL AS target_price,
o.stock AS source_stock, NULL AS target_stock
FROM source_products_demo AS o
WHERE NOT EXISTS (
SELECT 1 FROM target_products_demo AS d WHERE d.id = o.id
)
UNION ALL
SELECT d.id, 'only_target', NULL, d.price_cents,
NULL, d.stock
FROM target_products_demo AS d
WHERE NOT EXISTS (
SELECT 1 FROM source_products_demo AS o WHERE o.id = d.id
)
UNION ALL
SELECT o.id, 'modified', o.price_cents, d.price_cents,
o.stock, d.stock
FROM source_products_demo AS o
JOIN target_products_demo AS d ON d.id = o.id
WHERE o.name <> d.name
OR o.price_cents <> d.price_cents
OR (o.price_cents IS NULL AND d.price_cents IS NOT NULL)
OR (o.price_cents IS NOT NULL AND d.price_cents IS NULL)
OR o.stock <> d.stock
OR (o.stock IS NULL AND d.stock IS NOT NULL)
OR (o.stock IS NOT NULL AND d.stock IS NULL)
)
SELECT id, status, source_price, target_price,
source_stock, target_stock
FROM differences
ORDER BY id;The three branches below cover mutually exclusive cases by id. UNION ALL keeps every finding without an unnecessary duplicate-removal step. The status column tells a missing row apart from a NULL attribute on a row that exists.
Full report: five keys with differences
| id | Status | Source price | Target price | Source stock | Target stock |
|---|---|---|---|---|---|
| 2 | modified | 3000 | 3200 | 5 | 5 |
| 3 | modified | NULL | 1500 | 8 | 8 |
| 5 | modified | 0 | NULL | NULL | 0 |
| 6 | only_source | 5000 | NULL | 3 | NULL |
| 7 | only_target | NULL | 7000 | NULL | 2 |
A unique key stops the JOIN from multiplying combinations and turns the branches into a stable classification. If the key is composite, include every part of it in each JOIN and NOT EXISTS. If you find several rows per key, first decide whether they are errors or valid versions; do not remove duplicates just to make the comparison add up.
What we are comparing
Set up the example data
The source has product 6 and the target has product 7. Products 2, 3 and 5 changed; products 1 and 4 match. Product 4 has a NULL stock in both tables, while product 5 swaps zero and NULL between its attributes.
CREATE TABLE source_products_demo (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
price_cents INTEGER,
stock INTEGER
);
CREATE TABLE target_products_demo (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
price_cents INTEGER,
stock INTEGER
);
INSERT INTO source_products_demo VALUES
(1, 'Cable', 1000, 50),
(2, 'Keyboard', 3000, 5),
(3, 'Mouse', NULL, 8),
(4, 'Case', 2000, NULL),
(5, 'Adapter', 0, NULL),
(6, 'Base', 5000, 3);
INSERT INTO target_products_demo VALUES
(1, 'Cable', 1000, 50),
(2, 'Keyboard', 3200, 5),
(3, 'Mouse', 1500, 8),
(4, 'Case', 2000, NULL),
(5, 'Adapter', NULL, 0),
(7, 'Hub', 7000, 2);Download data and queries (.sql)
The file is ready for an empty SQLite database and contains the same examples as this guide. Run it once on a test connection that supports window functions. The course's teaching engine does not support all of these constructs, so use SQLite to reproduce the full case.
Here, id identifies the same product in both tables. The relevant attributes are the name, the price in cents and the stock. We treat two NULLs as matching (no information on either side), but we tell NULL apart from zero. The physical order of the rows plays no part in equality.
If each system generated its own ids, you need a shared business key or an explicit mapping. Do not join local ids just because it is convenient: you would be comparing different products. You also need to decide which attributes to leave out, such as a technical load date that changes without the product changing.
Comparison rules for the snapshots
| Decision | Example rule |
|---|---|
| Identity | unique id shared by both systems |
| Attributes | name, price_cents and stock |
| NULL vs. NULL | Not a difference |
| NULL vs. zero | Difference |
| Text | Compared using the columns' collation |
| Scope | Two snapshots taken at the same cut-off point |
How it works
Finding records missing from a table
Search by identity with NOT EXISTS. The next query returns products known in the source that have no matching key in the target:
SELECT o.id, o.name
FROM source_products_demo AS o
WHERE NOT EXISTS (
SELECT 1 FROM target_products_demo AS d
WHERE d.id = o.id
)
ORDER BY o.id;The result is id 6, Base. If you swap source and target, you get id 7, Hub. Searching in one direction only would miss one type of difference. This pattern is an anti-join; it does not need to compare prices to decide that the entity is missing.
Finding the same key with changed values, NULLs included
An INNER JOIN keeps the keys present in both tables, and then we check each attribute. Names are NOT NULL here, so an ordinary comparison is enough for them. Price and stock are optional, so we have to catch both a different value and a change from NULL to a value or from a value to NULL.
SELECT o.id, o.price_cents AS source_price,
d.price_cents AS target_price,
o.stock AS source_stock, d.stock AS target_stock
FROM source_products_demo AS o
JOIN target_products_demo AS d ON d.id = o.id
WHERE o.name <> d.name
OR o.price_cents <> d.price_cents
OR (o.price_cents IS NULL AND d.price_cents IS NOT NULL)
OR (o.price_cents IS NOT NULL AND d.price_cents IS NULL)
OR o.stock <> d.stock
OR (o.stock IS NULL AND d.stock IS NOT NULL)
OR (o.stock IS NOT NULL AND d.stock IS NULL)
ORDER BY o.id;Three changed products
| id | Source price | Target price | Source stock | Target stock |
|---|---|---|---|---|
| 2 | 3000 | 3200 | 5 | 5 |
| 3 | NULL | 1500 | 8 | 8 |
| 5 | 0 | NULL | NULL | 0 |
Product 3 would be missed if you only checked source_price <> target_price: an ordinary comparison with NULL is never true. Product 4 does not appear because its prices match and both stock values are NULL. That decision treats two missing values as matching data, not as proof that the real stock is known.
Do not replace NULL with a sentinel value such as zero for the comparison. Product 5 shows why that fails: its price goes from a known zero to unknown, and its stock goes from unknown to a known zero. Using COALESCE(column, 0) would hide both changes.
Edge cases
Comparing whole rows with EXCEPT in both directions
EXCEPT answers a different question: which complete rows in one set are not in the other. You must select the same columns, in the same order and with compatible types. Avoid SELECT *, because a schema change could alter the comparison.
SELECT id, name, price_cents, stock
FROM source_products_demo
EXCEPT
SELECT id, name, price_cents, stock
FROM target_products_demo
ORDER BY id;SELECT id, name, price_cents, stock
FROM target_products_demo
EXCEPT
SELECT id, name, price_cents, stock
FROM source_products_demo
ORDER BY id;The first direction returns ids 2, 3, 5 and 6; the second returns 2, 3, 5 and 7. Those outputs contain eight different row versions but only five affected products: the three changed ones appear with both their old and new versions. Do not add the two counts together to report how many entities changed.
In SQLite, EXCEPT removes duplicates and treats NULLs as equal when deciding whether rows match. That is fine for comparing sets, but it does not guarantee that the two tables hold the same number of copies of each row.
Without a unique key, compare the counts too
Picture two bags of names: the source holds Cable, Cable, Mouse; the target holds Cable, Mouse, Mouse. Both have three rows and the same distinct names, so an EXCEPT on the names would find no difference. Yet the number of copies has changed.
WITH source(name) AS (
VALUES ('Cable'), ('Cable'), ('Mouse')
), destination(name) AS (
VALUES ('Cable'), ('Mouse'), ('Mouse')
), counts AS (
SELECT name, COUNT(*) AS n_source, 0 AS n_target
FROM source GROUP BY name
UNION ALL
SELECT name, 0, COUNT(*)
FROM destination GROUP BY name
)
SELECT name, SUM(n_source) AS source_rows,
SUM(n_target) AS target_rows
FROM counts
GROUP BY name
HAVING SUM(n_source) <> SUM(n_target)
ORDER BY name;Differences in counts
| Name | Source rows | Target rows |
|---|---|---|
| Cable | 2 | 1 |
| Mouse | 1 | 2 |
To compare rows that have no identity, group by every relevant column and compare the counts. That tells you whether two tables hold the same bag of rows, but not which particular copy changed. The duplicate detection rule helps you spot that difference in the model.
NULL comparisons by engine
The explicit predicate in the changes query works with ordinary comparisons and IS NULL. Some engines offer a shorter way to say “the values differ, treating missing as a value”. Use the one your version supports:
Predicate to detect a changed attribute
| Engine | Short form |
|---|---|
| SQLite | o.stock IS NOT d.stock |
| PostgreSQL | o.stock IS DISTINCT FROM d.stock |
| SQL Server 2022+ | o.stock IS DISTINCT FROM d.stock |
| MySQL | NOT (o.stock <=> d.stock) |
Apply these forms attribute by attribute and combine them with OR when a single change is enough to flag the record. The reference on IS DISTINCT FROM and comparisons with NULL covers the differences in detail. IS NOT between two values is the SQLite form used in the next exercise; do not copy it as universal syntax.
EXCEPT is not available in every version. If your engine does not support it, use identity matching with NOT EXISTS and JOIN. The three-branch report does not need a FULL OUTER JOIN, which makes it easy to carry over to other systems. The examples were run in SQLite; the forms for other engines were checked against official documentation without running them on those servers.
Collation, snapshot timing and performance
For text, the collation decides whether capitals, accents or other variants count as different. Decide whether you need equality under business rules or strict equality of the stored value. Applying LOWER or TRIM across the board can hide changes you want to audit.
Compare snapshots taken at the same point in time. If the source keeps changing during an export and the target reflects a different time, some differences will just be that lag. Use a consistent read or exports with an agreed cut-off; the steps depend on the engine and on whether the data lives in one database or several.
The primary keys in the example prevent duplicate ids. On large tables, review indexes and access plans before repeating the full comparison. A checksum can be a useful extra check, but it does not replace the detailed report or guarantee equality: collisions are possible, and so are formatting differences. For amounts and approximate measurements, agree on units, precision and tolerance before comparing.
How to check it
WITH keys AS (
SELECT id FROM source_products_demo
UNION
SELECT id FROM target_products_demo
)
SELECT COUNT(*) AS total_keys,
COALESCE(SUM(CASE WHEN d.id IS NULL THEN 1 ELSE 0 END), 0) AS only_source,
COALESCE(SUM(CASE WHEN o.id IS NULL THEN 1 ELSE 0 END), 0) AS only_target,
COALESCE(SUM(CASE WHEN o.id IS NOT NULL AND d.id IS NOT NULL
AND (o.name IS NOT d.name
OR o.price_cents IS NOT d.price_cents
OR o.stock IS NOT d.stock)
THEN 1 ELSE 0 END), 0) AS modified,
COALESCE(SUM(CASE WHEN o.id IS NOT NULL AND d.id IS NOT NULL
AND o.name IS d.name
AND o.price_cents IS d.price_cents
AND o.stock IS d.stock
THEN 1 ELSE 0 END), 0) AS equal
FROM keys AS c
LEFT JOIN source_products_demo AS o ON o.id = c.id
LEFT JOIN target_products_demo AS d ON d.id = c.id;The four categories add up to the total
| Keys | Source only | Target only | Changed | Matching |
|---|---|---|---|---|
| 7 | 1 | 1 | 3 | 2 |
UNION lists each id once, and the two LEFT JOINs let you see both sides. The presence checks use id, which cannot be NULL, so a missing entity is never confused with an unknown stock. The counts 1 + 1 + 3 + 2 add up to seven; the matching rows are 1 and 4.