Duplicate natural keys with different ids
Group by the natural key and count distinct surrogate ids: more than one id per natural key means the same real-world thing is stored twice.
The task
order_items should hold one line per (order_id, product_id), but re-runs of an importer created several rows, each with its own surrogate id, for the same line. Those id groups are your merge candidates.
The snippet
Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.
SELECT order_id, product_id,
COUNT(*) AS line_copies,
COUNT(DISTINCT id) AS distinct_ids,
MIN(id) AS keep_id,
MAX(id) AS merge_id
FROM order_items
GROUP BY order_id, product_id
HAVING COUNT(DISTINCT id) > 1
ORDER BY line_copies DESC;
작동 방식
The natural key (order_id, product_id) is the GROUP BY; HAVING keeps keys stored under more than one surrogate id. MIN(id) is a sensible survivor and MAX(id) the newest copy; when line_copies is above 2 there are more ids in between, which the variant lists in full. If id is a real primary key, COUNT(*) and COUNT(DISTINCT id) are always equal; when they differ, the surrogate id itself is duplicated and you have a second problem to fix first.
Variations
Show the full rows to merge
WITH dupes AS (
SELECT order_id, product_id
FROM order_items
GROUP BY order_id, product_id
HAVING COUNT(*) > 1
)
SELECT oi.*
FROM order_items oi
JOIN dupes d
ON d.order_id = oi.order_id AND d.product_id = oi.product_id
ORDER BY oi.order_id, oi.product_id, oi.id;
Questions that come up
Natural key or surrogate id: which one defines a duplicate?
The natural key does: it identifies the real-world thing (this order line for this product), while surrogate ids merely distinguish stored copies. Duplicates on the natural key with different surrogate ids are the signature of a missing uniqueness enforcement. The data-quality fix is the merge now and the UNIQUE constraint after.
Keep reading
Related on SQLly
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.