Write SQL to return the latest order, status, or event for every entity.
Answer
Use ROW_NUMBER over a partition for each entity, order rows newest-first and keep row number one in an outer query. Include a deterministic secondary ordering column such as the primary key because MAX(timestamp) alone returns only the timestamp and can match several tied records.
Strong answer includes
- uses ROW_NUMBER with PARTITION BY entity key
- orders newest-first with a deterministic tie-breaker
- explains why MAX(timestamp) alone may not return one complete row
Practical example
Dialect · Portable SQLRuntime · SQLite sample DB
Runs against the resettable SQLite sample database used by the playground.
SQL
Result
Run the query to see the result.
Number rows newest-first inside each entity and keep row 1. MAX(created_at) alone returns only a timestamp and can match multiple tied rows.
Expected result: Exactly one newest row per entity that has data.