Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
QA interview question
Databases, SQL & BISQL languageMiddleCommonPractical

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

Solution · Latest row per entity
Dialect · Portable SQLRuntime · SQLite sample DB

Runs against the resettable SQLite sample database used by the playground.

SQL
SQLite · sample DB · browser sandbox
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.

#sql#window-functions#latest-row#ranking

Sources

PostgreSQL documentationPostgreSQL Global Development Group · Relational modelling, SQL, joins, constraints, transactions, concurrency, indexes, query plans and recovery