Conditionally Insert or Update Records
Problem statement
For this exercise, assume a table stores one integer value for each record identifier. Apply a batch of incoming records using the existence-based condition below.
Input tables
existing_records(record_id, value)is the initial table.incoming_records(record_id, value)contains the records to apply.- Each table has unique, non-null identifiers. An identifier may occur in both tables, and matching uses integer equality.
Conditional insert or update
- If an incoming identifier already exists, replace its stored value with the incoming value.
- If an incoming identifier is absent, insert a new row containing that identifier and value.
- Keep existing rows whose identifiers do not occur in the incoming table.
- A replacement applies even when the new value is smaller, zero, negative, or equal to the old value. Do not sum values or select the larger value.
Result
Complete the Pandas function apply_record_changes(existing_records, incoming_records). Return a DataFrame with exactly the columns record_id and value, in that order, and exactly one row per final identifier. Sort rows by record_id ascending. Either input table may be empty.
This is a finite table-state exercise using the Python option mentioned in the report. The return value represents the state after the batch; no external database, transaction protocol, or concurrent writers are part of the contract. The record schema, existence condition and result conventions are practice assumptions.
Table schema
Use the same input data with any supported language. Open the Schema tab in the editor to see the generated SQL setup or Pandas DataFrames.
existing_records
Initial record state.
| Column | Type | Nullable | Description |
|---|---|---|---|
| record_idPK | Integer | No | Unique integer identifier, matched by equality. |
| value | Integer | No | The complete scalar value stored for this identifier. |
incoming_records
Incoming values to insert or replace by identifier.
| Column | Type | Nullable | Description |
|---|---|---|---|
| record_idPK | Integer | No | Unique integer identifier, matched by equality. |
| value | Integer | No | The complete scalar value stored for this identifier. |
Expected result
Your query or function must return these columns.
| Column | Type | Nullable | Description |
|---|---|---|---|
| record_id | Integer | No | Unique integer identifier, matched by equality. |
| value | Integer | No | The complete scalar value stored for this identifier. |
Row order: must match exactly. Numeric tolerance: 0.
Constraints
- Each input table contains between
0and1000rows. - Every
record_idis an integer in[0, 10^9]and is unique within its input table. - Values are non-null integers in
[-10^9, 10^9]. - Input rows may appear in any order. The result contains at most
2000rows.