Dataford
Popular roles
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Browse
Browse All RolesEvery role hub, from analyst to MLBrowse All CompaniesCompany-specific interview loopsAll Interview GuidesThe full guide library
Top questions by role
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Top questions by skill
SQLPythonStatisticsMachine LearningA/B TestingSystem DesignGenerative AIProduct SenseMetricsBehavioral
Browse all questions →Try a mock interview
ExperiencesCoaching
New
Practice
Mock InterviewsTimed interview simulations with feedbackSuccess PathYour 6-week structured planModulesCurated lessons by topicWebinarsTalks from ex-Big Tech data leadsPlaygroundA free-form scratch editor
Learn
BlogInterview strategy and career adviceTech Job Market ReportHiring trends across data and AI rolesFor UniversitiesDataford for career centersAbout DatafordWho we are and how we build
Pricing
Get started
SQL First Record from Duplicates
00:00
5 left

SQL First Record from Duplicates

HardSQL · PostgreSQL

Problem

Write a SQL query to select only the first record of a duplicated row based on a specific timestamp or sequence number.

Treat rows with the same entity_id, event_type, and event_value as duplicates. Select the earliest timestamp, then the lowest sequence number, and use record_id as the final tie-breaker. Retain unique rows and place records with null timestamps after non-null timestamps.

Output

  1. One row per retained record, with columns record_id, entity_id, event_type, event_value, event_timestamp, sequence_number, and payload.
  2. Include exactly one row for each duplicate set and all unique rows.
  3. Order by entity_id, event_type, event_value with null values last, then record_id.

Schema

event_records
ColumnTypeDescription
record_idPKINTUnique record identifier
entity_idINTIdentifier of the entity associated with the event
event_typeVARCHAR(50)Type of recorded event
event_valueVARCHAR(100)Value used as part of the duplicate business key
event_timestampTIMESTAMPTZTimestamp associated with the event
sequence_numberINTSequence used to resolve timestamp ties
payloadVARCHAR(255)Additional event content
Tablesevent_records
Interviewer

Whenever you're ready, walk me through your approach or go straight to the code. The requirements and the one table are in the Question tab.

You need to log in / sign up to run or submit.
CodePostgreSQL
Sign up free to run your codeLog inLn 1
Run your query to see results here.