Skip to content
Onsite

Latest row per key (deduplicate by latest timestamp)

MediumP1Coding

Table events:

ColumnType
idint (primary key)
entity_idint
statustext
updated_attimestamptz

Each entity has many rows, one per status change. Write a query that returns the latest row for every entity: the one with the greatest updated_at. If two rows of an entity share the greatest updated_at, keep the one with the larger id.

Return the columns entity_id, status and updated_at, one row per entity.

Schema

CREATE TABLE events (
  id int PRIMARY KEY,
  entity_id int NOT NULL,
  status text NOT NULL,
  updated_at timestamptz NOT NULL
);

Example 1

Input
events: (1, 10, 'new', '2024-01-01 09:00+00'), (2, 10, 'paid', '2024-01-02 09:00+00'), (3, 11, 'new', '2024-01-01 12:00+00')
Output
10, paid, 2024-01-02 09:00:00+00 11, new, 2024-01-01 12:00:00+00

Constraints

  • PostgreSQL dialect.
  • Return rows in any order.
  • Each entity appears exactly once in the result.

Hints

PostgreSQL
Run checks the 2 visible tests, Submit all 5.