Latest Version by Timestamp
Company: Goldman Sachs
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
The `records` table stores versioned rows. Each `id` may have multiple versions with different `ts` values. For each `id`, return the row with the latest `ts` as `id`, `data`, `ts`, ordered by `id` ascending.
```hint Getting the whole row
A plain `GROUP BY id` can tell you the latest timestamp, but it cannot pick `data` from the right row by itself.
```
### Input Table(s)
`records` has one row per version.
| Column | Type | Meaning |
|---|---|---|
| record_id | INT | Row identifier (primary key) |
| id | INT | Entity the version belongs to, NOT NULL |
| data | VARCHAR(255) | Payload of this version, may be NULL |
| ts | TIMESTAMP | When this version was written, NOT NULL |
Keys: `record_id` is the primary key. One `id` can appear in many rows.
### Output Contract
- Columns in this order: `id`, `data`, `ts`.
- One row per distinct `id`: the version with the latest `ts`.
- Order by `id` ascending. Each `id` appears once, so this ordering is unique.
- Return `data` and `ts` exactly as stored, with no formatting.
### Example
Input `records`:
| record_id | id | data | ts |
|---|---|---|---|
| 1 | 1 | alpha-v1 | 2024-01-01 10:00:00 |
| 2 | 1 | alpha-v2 | 2024-01-02 10:00:00 |
| 3 | 1 | alpha-v3 | 2024-01-03 10:00:00 |
| 4 | 2 | beta-v1 | 2024-01-01 09:00:00 |
| 5 | 2 | beta-v2 | 2024-01-05 09:00:00 |
| 6 | 3 | gamma-v1 | 2024-02-01 08:00:00 |
Expected output:
| id | data | ts |
|---|---|---|
| 1 | alpha-v3 | 2024-01-03 10:00:00 |
| 2 | beta-v2 | 2024-01-05 09:00:00 |
| 3 | gamma-v1 | 2024-02-01 08:00:00 |
For id=1, the latest ts is 2024-01-03 with data 'alpha-v3'. For id=2, the latest is 2024-01-05 with 'beta-v2'. For id=3, only one row exists, so it is returned.
### Constraints and Clarifications
- The table has between 1 and 10,000 rows.
- For each `id`, the maximum `ts` is unique, so there is never a tie for the latest version.
- `data` may be NULL. If the latest version has NULL `data`, return that row with NULL in the `data` column.
- An `id` with only one version returns that version.
Overview: A SQL problem on versioned records: for every id, return the data and timestamp of its most recent version, sorted by id. It tests the greatest-row-per-group pattern, recovering the full row after an aggregate, and keeping NULL values in columns that are not part of the key.