Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

SQL Row Before Latest

MediumSQL · PostgreSQL00:00
Practice interviewer
In session
5 left
00:00

Your question is SQL Row Before Latest. Start with the requirements and the two tables on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Datavant's entity resolution workflows retain multiple observations for each linked entity, including records received from different source systems. Write a PostgreSQL query to return the observation immediately before the latest observation for every entity.

Requirements

  1. Rank observations independently within each entity_id by observed_at descending. Use observation_id descending as a deterministic tie-breaker.
  2. Return only the row ranked immediately before the latest row, meaning rank 2.
  3. Include entities that have at least two observations, along with the entity name and observation details.
  4. Order the final result by entity_id.

Schema

linked_entities
ColumnTypeDescription
entity_idPKINTEGERUnique Datavant-linked entity identifier
entity_nameVARCHAR(100)Display name for the linked entity
entity_typeVARCHAR(30)Entity classification
entity_observations
ColumnTypeDescription
observation_idPKINTEGERUnique observation identifier
entity_idINTEGERReferences linked_entities.entity_id
source_systemVARCHAR(50)System that supplied the observation
observed_atTIMESTAMPTime the observation was recorded
observation_statusVARCHAR(20)Processing status
observed_valueTEXTValue captured by the observation
Tableslinked_entitiesentity_observations
Your solutionPostgreSQL
You need to log in / sign up to run or submit.
Run a query to see results