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
Start free
SQL for Consecutive Treatment Gaps
00:00
5 left

SQL for Consecutive Treatment Gaps

HardSQL · PostgreSQL

Problem

Verily’s clinical research workflows need to identify periods when a patient had no recorded treatment activity. Given a patient event log, write a PostgreSQL query that finds consecutive treatment events separated by more than 90 days.

Requirements

  1. Consider only rows where event_type = 'treatment' and event_date is not NULL.
  2. Compare each treatment event with the immediately preceding treatment event for the same patient. Other event types, such as visits and lab results, must not reset the treatment sequence.
  3. Return the patient, the start and end dates of each qualifying gap, and the number of elapsed days.
  4. Include only gaps strictly greater than 90 days and order the results by patient and gap start date.

Output details

  • Return columns named patient_id, gap_start, gap_end, and gap_days, in that order.
  • Sort by patient_id ascending, then gap_start ascending.
  • Do not deduplicate distinct treatment events when producing qualifying gaps.
  • Treat treatment events sharing the current event's event_date as ineligible preceding events.

Schema

patient_event_log
ColumnTypeDescription
event_idPKINTUnique clinical event identifier
patient_idINTIdentifier of the patient associated with the event
event_typeVARCHAR(30)Clinical event classification, such as treatment, visit, or lab
event_dateDATEDate on which the clinical event occurred
Tablespatient_event_log
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.

Sign up free to run or submit. Log in
CodePostgreSQL
Sign up free to run your code. Your draft is saved.Run with a free accountLog inLn 1
Run your query to see results here.