runtime
58 / 88

task INSERT / UPDATE / DELETE · hard

Build a replay-safe ledger load

Merge market_load_feed into market_ledger. For each external_id choose the highest source version, breaking ties by greatest feed id. Insert missing keys and replace a target only when the source version is at least its version. Return the entire final ledger.

what to return

Columns
external_idversionamount in this order
Rows
3 rows · in the order asked
Watch for
Do not delete target-only or newer target rows. Z starts at version 9, amount 90 and must survive its stale feed record.
Order by external_id. Your complete script is tested twice on the same database to check that it is safe to rerun. This is checked with both the sample data and different data.
The feed is immutable; do not clear it or use a one-shot marker to bypass processing.
Skill
Implement an idempotent upsert that handles duplicate source versions and late stale records. Refresher: Idempotent incremental UPSERT & stale updates →

expected result

Your query should return exactly these columns and values. Run it and compare.

expected result3 rows · in this order
external_idversionamount
X225
Y15
Z990

all 3 rows

data you can query

Sample rows from each table. Each column shows its type underneath; → marks a link to another table.

market_load_feed4 columns · 5 rows
idinteger · keyexternal_idtextversionintegeramountinteger
1X110
2X220
3X225
4Y15
5Z2999

all 5 rows

market_ledger3 columns · 2 rows
external_idtext · keyversionintegeramountinteger
X110
Z990

all 2 rows

solution.sql
 

Hints and the answer are always available. Using them counts the question as solved with help.