records is an insert-only table. Every change to a record is written as a new row, and no row is ever updated or removed in place. A record's current state is its row with the latest created_at.
Return record_id, field_value, status and created_at of each record's current state, excluding records whose latest status is 'deleted'. Order by record_id ascending.
Input Table(s)
Table: records
| Column | Type | Meaning |
|---|
| id | INT | Row id. Primary key, auto-increment. |
| record_id | INT | The logical record this version belongs to. NOT NULL. |
| field_value | VARCHAR(255) | The record's value in this version. May be NULL. |
| status | VARCHAR(50) | One of 'active', 'updated', 'deleted'. NOT NULL, defaults to 'active'. |
| created_at | DATETIME | When this version was written. NOT NULL. |
Primary key: id. A record_id appears on one or more rows, and (record_id, created_at) is unique.
Output Contract
-
Columns, in this order:
record_id
,
field_value
,
status
,
created_at
.
-
One row per
record_id
whose latest row does not have
status = 'deleted'
.
-
Every value comes unchanged from that latest row.
-
Sort by
record_id
ascending. There is one row per
record_id
, so this order is unique.
-
No rounding applies.
Example
records
| id | record_id | field_value | status | created_at |
|---|
| 1 | 101 | alpha | active | 2024-01-01 09:00:00 |
| 2 | 101 | alpha-v2 | updated | 2024-01-03 10:00:00 |
| 3 | 102 | beta | active | 2024-01-02 08:00:00 |
| 4 | 102 | beta | deleted | 2024-01-04 12:00:00 |
| 5 | 103 | gamma | active | 2024-01-01 07:00:00 |
| 6 | 103 | gamma | deleted | 2024-01-02 07:00:00 |
| 7 | 103 | gamma-restored | active | 2024-01-05 15:00:00 |
| 8 | 104 | NULL | active | 2024-01-06 11:00:00 |
Expected result
| record_id | field_value | status | created_at |
|---|
| 101 | alpha-v2 | updated | 2024-01-03 10:00:00 |
| 103 | gamma-restored | active | 2024-01-05 15:00:00 |
| 104 | NULL | active | 2024-01-06 11:00:00 |
Record 101's newest row is the 'updated' version from January 3, so that row is returned. Record 102's newest row is a delete, so the record is left out. Record 103 was deleted on January 2 and restored by a newer 'active' row, so it appears with its restored value. Record 104 has a single row and is returned with its NULL field_value.
Constraints and Clarifications
-
The table holds 1 to 10,000 rows.
-
status
is always one of
'active'
,
'updated'
,
'deleted'
. Only
'deleted'
removes a record from the result;
'updated'
is a live state.
-
created_at
is unique within a
record_id
, so every record has exactly one latest row.
-
A deleted record can be restored by a newer row. When its latest row is not a delete, the record is returned.
-
field_value
can be NULL. Return it as NULL.