Merge duplicate rows by re-parenting children
Pick one survivor line per product across the three orders, give it the combined quantity and move it to order 101, then delete the leftover lines and the empty duplicate orders.
The task
Orders 102 and 103 are duplicates of order 101. Their order_items must move to 101, but 101 may already have a line for the same product, and 102 and 103 may both have one, so colliding lines must merge their quantities instead of moving blindly.
The snippet
Written for PostgreSQL.
-- Run everything below in one transaction (BEGIN; ... COMMIT;)
-- 1. One survivor line per product, carrying the combined quantity
WITH lines AS (
SELECT id,
ROW_NUMBER() OVER (
PARTITION BY product_id
ORDER BY CASE WHEN order_id = 101 THEN 0 ELSE 1 END, id
) AS rn,
SUM(quantity) OVER (PARTITION BY product_id) AS total_quantity
FROM order_items
WHERE order_id IN (101, 102, 103)
)
UPDATE order_items oi
SET order_id = 101,
quantity = l.total_quantity
FROM lines l
WHERE l.id = oi.id
AND l.rn = 1;
-- 2. Whatever is still on 102/103 was folded into a survivor
DELETE FROM order_items WHERE order_id IN (102, 103);
-- 3. Retire the now-empty duplicate orders
DELETE FROM orders WHERE id IN (102, 103);
Cómo funciona
The CTE ranks the lines of all three orders per product, preferring a line already on 101 and then the lowest id, and computes each product's total quantity across the three. The UPDATE moves each rank-1 line to 101 with that total, so every product ends up with exactly one line on the survivor. Every line still pointing at 102 or 103 afterwards is a copy whose quantity was just counted, which makes step 2 a plain DELETE. UPDATE ... FROM with a CTE is PostgreSQL syntax; SQL Server accepts the same shape with UPDATE oi SET ... FROM order_items oi JOIN lines l ON l.id = oi.id. Run the variant first and compare its totals with order 101 afterwards.
Variations
Preview the merge (any engine)
SELECT product_id,
COUNT(*) AS lines_now,
SUM(quantity) AS quantity_after_merge
FROM order_items
WHERE order_id IN (101, 102, 103)
GROUP BY product_id
ORDER BY product_id;
Questions that come up
What happens to child data that has no equivalent on the survivor?
It moves as it is: a product only 102 had becomes a line on 101 with its original quantity, because it is the only line in its partition. Summing quantities is the right merge rule for order lines; for other children you may need a different one, such as keeping the newest note or concatenating comments, or tagging moved rows with their source id so the merge stays auditable.
Keep reading
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.